有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在批处理中使用JDBC preparedStatement

我正在使用Statement的批处理来查询我的数据库。 我现在做了一些研究,我想重写我的应用程序,改为使用preparedStatement,但我很难想出如何向preparedStatement批添加查询

这就是我现在正在做的:

private void addToBatch(String sql) throws SQLException{
sttmnt.addBatch(sql);
batchSize++;
if (batchSize == elementsPerExecute){
    executeBatches();
}
}

其中sttmntStatement类型的类成员

我想做的是使用preparedStatementsetString(int, String)方法设置一些动态数据,然后将其添加到批处理中

不幸的是,我不完全理解它是如何工作的,以及如何将setString(int, String)用于批处理中的特定sql,或者为我拥有的每个sql创建一个新的preparedStatemnt,然后将它们全部加入到一个批处理中

有可能吗?还是我对^{的理解真的遗漏了什么


共 (3) 个答案

  1. # 1 楼答案

    例如,有了PreparedStatement,你就有了通配符

    Sring query = "INSERT INTO users (id, user_name, password) VALUES(?,?,?)";
    PreparedStatement statement = connection.preparedStatement(query);
    for(User user: userList){
        statement.setString(1, user.getId()); //1 is the first ? (1 based counting)
        statement.setString(2, user.getUserName());
        statement.setString(3, user.getPassword()); 
        statement.addBatch();
    }
    

    这将使用上面显示的查询创建1PreparedStatement。当你想插入或是想做什么的时候,你可以在列表中循环。当你想处决你的时候

    statement.executeBatch();
    statement.clearBatch(); //If you want to add more, 
    //(so you don't do the same thing twice)
    
  2. # 2 楼答案

    我在这里专门为MySQL添加了一个额外的答案

    我发现做一批插入的时间与做单个插入的时间长度相似,即使是在一批事务中

    我将参数rewriteBatchedStatements=true添加到我的jdbc url中,并看到了一个显著的改进——在我的例子中,一批200个插入从125毫秒变成了125毫秒。如果不使用该参数,则将其设置为大约10到15毫秒。使用参数

    MySQL and JDBC with rewriteBatchedStatements=true

  3. # 3 楼答案

    阅读section 6.1.2 of this document以获取示例。基本上,您使用相同的语句对象,并在设置所有占位符后调用批处理方法Another IBM DB2 example它应该适用于任何JDBC实现。从第二个站点:

    try {
      connection con.setAutoCommit(false);        
      PreparedStatement prepStmt = con.prepareStatement(    
        "UPDATE DEPT SET MGRNO=? WHERE DEPTNO=?");
      prepStmt.setString(1,mgrnum1);            
      prepStmt.setString(2,deptnum1);
      prepStmt.addBatch();                      
    
      prepStmt.setString(1,mgrnum2);                        
      prepStmt.setString(2,deptnum2);
      prepStmt.addBatch();
      int [] numUpdates=prepStmt.executeBatch();
      for (int i=0; i < numUpdates.length; i++) {
        if (numUpdates[i] == -2)
          System.out.println("Execution " + i + 
            ": unknown number of rows updated");
        else
          System.out.println("Execution " + i + 
            "successful: " + numUpdates[i] + " rows updated");
      }
      con.commit();
    } catch(BatchUpdateException b) {
      // process BatchUpdateException
    }