[英]using JDBC preparedStatement in a batch
我使用Statement
的批处理来查询我的数据库。 Iv'e现在做了一些研究,我想重写我的应用程序使用preparedStatement
代替,但我有很难搞清楚如何查询添加到preparedStatement
批。
这就是我现在正在做的事情:
private void addToBatch(String sql) throws SQLException{
sttmnt.addBatch(sql);
batchSize++;
if (batchSize == elementsPerExecute){
executeBatches();
}
}
其中sttmnt
是Statement
类型的类成员。
我想要做的是使用preparedStatement
的setString(int, String)
方法设置一些动态数据,然后将其添加到批处理中。
不幸的是,我不完全理解它是如何工作的,以及如何将setString(int, String)
用于批处理中的特定sql,或者为我拥有的每个sql创建一个新的preparedStatemnt
,然后将它们全部连接到一个批处理。
有可能这样做吗? 或者我是否真的错过了对preparedStatement
理解?
有关示例,请阅读本文档的6.1.2节 。 基本上,您使用相同的语句对象,并在设置所有占位符后调用批处理方法。 另一个适用于任何JDBC实现的IBM DB2示例 。 从第二个网站:
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网址,并看到了一个显着的改进 - 在我的情况下,一批200个插入从125毫秒。 没有参数约10至15毫秒。 用参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.