繁体   English   中英

Java JDBC executeBatch

[英]Java JDBC executeBatch

我试图在数据库中执行很多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)....

首先,您应该使用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记录之后执行批处理可能更好。 我将其代码保留为“读者练习”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM