Java JDBC executeBatch

时间:2018-06-06 17:25:00

标签: java database jdbc

我试图在我的数据库中执行大量INSERT命令。

try{
    int Records[];
    Statement title = write.getConnection().createStatement();
    Title titleFilter = application.Title.getTitle();
    ResultSet rs = titleFilter.getTitleData();

    while(rs.next()){;
        String add = ("INSERT INTO title VALUES ("
                + "'" + rs.getInt(1) + "'"+","
                + "'" +rs.getString(2)+ "'" +","
                + "'" +rs.getString(3) + "'"+","
                + "'" +rs.getInt(4)+ "'" +","
                + "'" +rs.getInt(5)+ "'" +","
                + "'" +rs.getInt(6) + "'"+","
                + "'" +rs.getString(7)+ "'" +","
                + "'" +rs.getInt(8) + "'"+","
                +"'" + rs.getInt(9)+ "'" +","
                + "'" +rs.getInt(10)+ "'" +","
                + "'" +rs.getString(11)+ "'" +","
                +"'" + rs.getString(12) + "'"+")"
        );
        title.addBatch(add);
        System.out.println(add);
        title.executeBatch();
    }

我知道在添加表达式后立即执行批处理有点愚蠢。我改变它来发现我的错误。

每次我尝试运行程序时,此代码部分只插入六个表达式。我改变了很多东西以找到我的错误,但我想我永远找不到。此外,我得到了这个例外

org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"
  Position: 48
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2310)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2023)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:217)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:421)
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:318)....

1 个答案:

答案 0 :(得分:4)

首先,您应该使用PreparedStatement;这将帮助您避免语法错误(在连接Java String时很难看到)等等。其次,您正在执行每个循环的批处理,这违背了使用批处理的目的。

以下是使用PreparedStatement

的示例
String sql = "INSERT INTO title VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement title = write.getConnection().prepareStatement(sql);
     ResultSet rs = titleFilter.getTitleData()) {

    while (rs.next()) {
        title.setInt(1, rs.getInt(1));
        title.setString(2, rs.getString(2));
        // ... do this for all the parameters ...

        title.addBatch(); // add to batch and move to next loop (if rs.next() returns true)
    }

    title.executeBatch(); // executed after loop

} catch (SQLException ex) {
    ex.printStackTrace(); // or do what you need to when an error occurs
}

此示例还使用try-with-resources

修改

正如Ivan的评论中所提到的,在每个 X 记录之后执行批处理可能会更好。我将这段代码留给读者作为"练习#34;