【发布时间】: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 并且它起作用了。不过感谢您的帮助! :)