码迷,mamicode.com
首页 > 数据库 > 详细

关于DBUtils中QueryRunner看批量删除语句batch

时间:2017-11-21 23:57:34      阅读:335      评论:0      收藏:0      [点我收藏+]

标签:param   二维   batch   new   数组   target   null   实现   dba   

//批量删除

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

标签:param   二维   batch   new   数组   target   null   实现   dba   

原文地址:http://www.cnblogs.com/nizuimeiabc1/p/7875707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!