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

//批量删除

1
2
3
4
5
6
7
8
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

posted @   ppjj  阅读(3348)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示