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

本文介绍了一种使用Java和C3P0连接池批量删除数据库中图书记录的方法。通过构造一个包含待删除ID的二维数组参数,并利用PreparedStatement进行预编译SQL语句,实现了批量删除的功能。文章详细解释了如何通过循环填充PreparedStatement并调用addBatch方法,最后执行executeBatch完成批量删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//批量删除

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++) {//循环行数,决定SQL语句执行的次数
params[i] = new Object[]{ids[i]};//给低维也就是列数“?”赋值,每行只给一列赋值,决定每条SQL语句的参数个数
}
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值