1

我正在尝试将我的表格输出为 .csv 文件。我正在使用sqlite-jdbc java 库来执行我的查询。以下是声明:

.mode csv
.output test.csv
select * from geninfo;
.output stdout

这是我的java代码:

try {
            try {
                // create a database connection
                Class.forName("org.sqlite.JDBC");
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(SQLite.class.getName()).log(Level.SEVERE, null, ex);
            }
            connection = DriverManager.getConnection("jdbc:sqlite:702Data.db");
            Statement statement = connection.createStatement();
            statement.setQueryTimeout(30);  // set timeout to 30 sec.
            statement.executeUpdate("create table if not exists geninfo (id TEXT, DeviceID TEXT)");
            statement.executeUpdate(".mode csv");
            statement.executeUpdate(".output test.csv");
            statement.executeUpdate("select * from geninfo;");
            statement.executeUpdate(".output stdout");

            ResultSet rs = statement.executeQuery("select * from geninfo");
            while (rs.next()) {
                // read the result set
                System.out.println("DeviceID = " + rs.getString("DeviceID"));
                System.out.println("id = " + rs.getInt("id"));
            }
        } catch (SQLException e) {
            // if the error message is "out of memory", 
            // it probably means no database file is found
            System.err.println(e.getMessage());
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                // connection close failed.
                System.err.println(e);
            }
        }
    }

我尝试在句点周围添加括号并删除句点,两者都会导致相同的语法错误。

4

1 回答 1

1

Those commands are SQLite console commands, not pure SQL. JDBC can only handle SQL.

If you want to do this from java, try executing the shell command to open the console using ProcessBuilder and feed it the commands via its InputStream.

However, if calling from java is not necessary, you may be better served writing a shell script of some sort and using that directly, or calling the script from java.

If all you are using SQLite for is to parse the CSV file, consider not using SQLite at all and instead load the data directly from the file into your code using one of the several open source CSV parsing libraries out there. This approach will be order of magnitude faster and simpler.

于 2013-07-02T20:59:03.153 回答