admin

使用不同的SQL语句批处理PreparedStatement

sql

我想知道Java是否有可能

String A = "UPDATE blah set x=? y=? z=?"
String B = "UPDATE blah set a=? b=? c=? d=?"

我想有一个准备好的声明,主要是为了提高速度,其次是为了提高安全性。我希望能够填写A的绑定变量,执行A,B的绑定变量并执行B,然后提交整个事务。有没有更好的方法可以做到这一点?


阅读 362

收藏
2021-07-01

共1个答案

admin

您可以利用多个PreparedStatement获得所需的结果:

// Prepare code for PreparedStatement #1
String varOne = "A";
String varTwo = "B";
String varThree = "C";

String queryOne = "UPDATE blah set x=? y=? z=?"
PreparedStatement firstStmt = conn.prepareStatement(queryOne);

firstStmt.setString(1, varOne);
firstStmt.setString(2, varTwo);
firstStmt.setString(3, varThree);

firstStmt.executeUpdate();
conn.commit();

// Prepare code for PreparedStatement #2
String varOneB = "X";
String varTwoB = "Y";
String varThreeB = "Z";
String varFourB = "A";

String queryOne = "UPDATE blah set a=? b=? c=? d=?"
PreparedStatement secondStmt = conn.prepareStatement(queryTwo);

secondStmt.setString(1, varOneB);
secondStmt.setString(2, varTwoB);
secondStmt.setString(3, varThreeB);

secondStmt.executeUpdate();
conn.commit();
2021-07-01