什么导致我的SQLite查询中的“near”。“:语法错误”?

时间:2013-07-02 14:55:10

标签: java sqlite jdbc

我正在尝试output my table as a .csv file。我正在使用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);
            }
        }
    }

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

1 个答案:

答案 0 :(得分:1)

这些命令是SQLite控制台命令,而不是纯SQL。 JDBC只能处理SQL。

如果您想从java执行此操作,请尝试执行shell命令以使用ProcessBuilder打开控制台,并通过其InputStream将命令提供给它。

但是,如果不需要从java调用,那么编写某种shell脚本并直接使用它或从java调用脚本可能会更好。

如果你正在使用的SQLite是解析CSV文件,那么考虑根本不使用SQLite,而是使用几个开源CSV解析库中的一个将数据直接从文件加载到你的代码中。这种方法将更快,更简单。