在批处理中使用JDBC preparedStatement

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

这就是我现在正在做的事情:

 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 ,然后将它们全部连接到一个批处理。

有可能这样做吗? 或者我是否真的错过了对preparedStatement理解?

有关示例,请阅读本文档的6.1.2节 。 基本上,您使用相同的语句对象,并在设置所有占位符后调用批处理方法。 另一个IBM DB2示例应该适用于任何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 } 

例如,使用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(); } 

这将使用上面显示的查询创建1个PreparedStatement 。当您要插入或任何您想要的内容时,您可以遍历列表。 如果你想执行你,

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

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

我发现进行一批插入的时间类似于单个插入的时间长度,即使是批处理周围的单个事务也是如此。

我将参数rewriteBatchedStatements=true添加到我的jdbc url,并看到了一个显着的改进 – 在我的情况下,一批200个插入从125毫秒。 没有参数约10至15毫秒。 用参数。

请参阅使用rewriteBatchedStatements = true的MySQL和JDBC

使用JDBC在没有PreparedStatement的情况下批量插入

  int a= 100; try { for (int i = 0; i < 10; i++) { String insert = "insert into usermaster" + "(" + "userid" + ")" + "values(" + "'" + a + "'" + ");"; statement.addBatch(insert); System.out.println(insert); a++; } dbConnection.commit(); } catch (SQLException e) { System.out.println(" Insert Failed"); System.out.println(e.getMessage()); } finally { if (statement != null) { statement.close(); } if (dbConnection != null) { dbConnection.close(); } }