Hoo*_*oli 6 java sql-injection jdbc prepared-statement batch-processing
使用一个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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
摘自:http://www.mkyong.com/jdbc/jdbc-preparedstatement-example-batch-update/
但是,我正在寻找一种在不同的 sql查询上执行批处理事务的方法.即INSERT INTO TABLE A与INSERT INTO TABLE B无的SQL注入攻击的风险.我知道准备语句是避免此类攻击的首选方法,但我不知道在区分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();
}
Run Code Online (Sandbox Code Playgroud)
另外,请注意术语.谈论"批量交易"有点含糊不清:
addBatch并且executeBatch是将多个语句作为单个批处理(传输)发送到服务器的机制的一部分.这会影响语句发送(传输)到数据库服务器的方式.
数据库事务是一种机制,通过该机制将许多语句作为一个完整的组处理,即整个组将被处理("已提交")或整个组将被丢弃("回滚").的Connection#setAutoCommit(),Connection#commit()和Connection#rollback()方法来控制这种行为.这会影响数据库服务器执行语句的方式.
| 归档时间: |
|
| 查看次数: |
5552 次 |
| 最近记录: |