gpt4 book ai didi

java - 具有不同 sql 查询的批处理 preparedstatement

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:05:06 26 4
gpt4 key购买 nike

我找到了现有问题 similar对于这个实际上没有明确答案的问题。

带有一个 sql 查询的普通批准备语句看起来像这样:

private static void batchInsertRecordsIntoTable() throws SQLException {

Connection dbConnection = null;
PreparedStatement preparedStatement = null;

String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";

try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);

dbConnection.setAutoCommit(false);

preparedStatement.setInt(1, 101);
preparedStatement.setString(2, "mkyong101");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement.addBatch();

preparedStatement.setInt(1, 102);
preparedStatement.setString(2, "mkyong102");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement.addBatch();

preparedStatement.setInt(1, 103);
preparedStatement.setString(2, "mkyong103");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement.addBatch();

preparedStatement.executeBatch();

dbConnection.commit();

System.out.println("Record is inserted into DBUSER table!");

} catch (SQLException e) {

System.out.println(e.getMessage());
dbConnection.rollback();

} finally {

if (preparedStatement != null) {
preparedStatement.close();
}

if (dbConnection != null) {
dbConnection.close();
}

}

}

取自:http://www.mkyong.com/jdbc/jdbc-preparedstatement-example-batch-update/

但是,我正在寻找一种方法来对不同 sql 查询执行批量事务。即 INSERT INTO TABLE AINSERT INTO TABLE B 没有 SQL 注入(inject)攻击的风险。我知道准备语句是避免此类攻击的首选方法,但我不知道有什么方法可以在区分 SQL 查询时执行批处理事务?

最佳答案

对于两 (2) 个不同的 SQL 查询,您将需要两 (2) 个不同的 PreparedStatement 对象,每个对象都有自己的批处理,但是您可以在要发送对服务器的查询:

try (
PreparedStatement thisPs = conn.prepareStatement("INSERT INTO thisTable (thisId, thisText) VALUES (?,?)");
PreparedStatement thatPs = conn.prepareStatement("INSERT INTO thatTable (thatId, thatText) VALUES (?,?)")) {

thisPs.setInt(1, 1);
thisPs.setString(2, "thisText1");
thisPs.addBatch();

thatPs.setInt(1, 1);
thatPs.setString(2, "thatText1");
thatPs.addBatch();

thisPs.setInt(1, 2);
thisPs.setString(2, "thisText2");
thisPs.addBatch();

thatPs.setInt(1, 2);
thatPs.setString(2, "thatText2");
thatPs.addBatch();

thisPs.executeBatch();
thatPs.executeBatch();
}

另外,请注意术语。谈论“批量交易”有点模棱两可:

  • addBatchexecuteBatch 是将多个语句作为单个 batch(传输)发送到服务器的机制的一部分。这会影响语句发送(传输)到数据库服务器的方式。

  • 数据库事务是一种机制,通过该机制可以将多个语句作为一个完整的组进行处理,即整个组将被处理("committed”)或整个组将被丢弃(“回滚”)。 Connection#setAutoCommit()Connection#commit()Connection#rollback() 方法控制此行为。这会影响数据库服务器执行语句的方式。

关于java - 具有不同 sql 查询的批处理 preparedstatement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34041410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com