1. 程式人生 > >關於DBUtils中QueryRunner看批量刪除語句batch

關於DBUtils中QueryRunner看批量刪除語句batch

stmt run except for循環 dbutils c3p0 true pub pty

//批量刪除

public void delBooks(String[] ids) throws SQLException {
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
Object[][] params = new Object[ids.length][];//高維確定執行sql語句的次數,低維是給?賦值
for (int i = 0; i < params.length; i++) {
params[i] = new Object[]{ids[i]};//給“?”賦值
}
qr.batch("delete from books where id=?", params);
}

源碼實現:

public int[] batch(String sql, Object[][] params) throws SQLException {
Connection conn = this.prepareConnection();

return this.batch(conn, true, sql, params);
}

private int[] batch(Connection conn, boolean closeConn, String sql, Object[][] params) throws SQLException {
if (conn == null) {
throw new SQLException("Null connection"); } if (sql == null) { if (closeConn) { close(conn); } throw new SQLException("Null SQL statement"); } if (params == null) { if (closeConn) { close(conn); } throw new SQLException("Null parameters. If parameters aren‘t need, pass an empty array."); } PreparedStatement stmt
= null; int[] rows = null; try { stmt = this.prepareStatement(conn, sql); for (int i = 0; i < params.length; i++) { this.fillStatement(stmt, params[i]); stmt.addBatch(); } rows = stmt.executeBatch(); } catch (SQLException e) { this.rethrow(e, sql, (Object[])params); } finally { close(stmt); if (closeConn) { close(conn); } } return rows; }

解讀: 因為params是一個二維數組, 所以往preparedStatement中賦值的時候使用了for循環, 然後通過preparedstatement.addBatch() 進行批量添加, 然後執行executeBatch()進行操作.

本文轉自:https://www.cnblogs.com/wang-meng/p/5525389.html

關於DBUtils中QueryRunner看批量刪除語句batch