【问题标题】:H2 Database, merge into table using Java CSVREADH2 数据库,使用 Java CSVREAD 合并到表中
【发布时间】:2014-09-27 21:46:01
【问题描述】:

美好的一天!我有以下代码连接到 H2 数据库并使用 Java 执行查询。但是,只有 CALL CSVWRITE 对我有用。

这是我的代码:

public static Result tagImport() {
    String user = session("username");
    Connection connection = null;
    ResultSet resultSet = null;
    Statement statement = null;
    try {
        Class.forName("org.h2.Driver");
        connection = DriverManager.getConnection(
                "jdbc:h2:file:~/data/db", "sa", "");
        statement = connection.createStatement();
        resultSet = statement
                .executeQuery("CALL CSVWRITE('textfiles/tags.csv', 'SELECT * FROM TAG');");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        return ok(dbSuccess.render(user));
}

public static Result tagExport() {
    String user = session("username");
    Connection connection = null;
    ResultSet resultSet = null;
    Statement statement = null;
    try {
        Class.forName("org.h2.Driver");
        connection = DriverManager.getConnection(
                "jdbc:h2:file:~/data/db", "sa", "");
        statement = connection.createStatement();
        resultSet = statement.executeQuery("MERGE INTO TAG (SELECT * FROM CSVREAD('textfiles/tags.csv'));");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        return ok(dbSuccess.render(user));
}

如您所见,唯一的区别是要执行的查询。我对两者都使用了相同的方法,但它似乎不适用于 tagExport 函数。我只想再次连接到数据库并将我使用 tagImport 函数创建的 csv 文件插入到表中。请帮忙。谢谢!

【问题讨论】:

  • 你能试试MERGE INTO TAG SELECT * FROM CSVREAD('textfiles/tags.csv')吗?
  • 谢谢,但查询仍然不起作用。我真的无法确定问题所在。
  • 它对我有用。您需要提供更多信息:tag 表的create table 语句、错误消息和堆栈跟踪以及一些数据。
  • 我想我已经明白了。我将 resultSet 变量转换为 int 并将 statement.executeQuery 替换为 statement.executeUpdate 并且它起作用了。不过感谢您的帮助! :)

标签: java sql database csv h2


【解决方案1】:

对于MERGE 语句,您需要使用Statement.executeUpdate() 而不是executeQuery()

【讨论】:

  • 是的。这绝对是解决这个问题的方法。另外,我已经用这个实现了上面的代码:ResultSet resultSet = null;int resultSet = 0;,因为 executeUpdate() 返回一个 int 值。这就是全部。谢谢!
  • 顺便说一句,对不起,我不能投票赞成你的答案。我还没有15个声望。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-18
  • 1970-01-01
  • 2013-07-14
  • 2016-08-07
  • 2012-08-06
  • 1970-01-01
相关资源
最近更新 更多