JDBC 批量处理(插入,删除,更新)

本文介绍了如何在Java中执行批量的SQL操作,包括插入、更新等,并详细讲解了使用addBatch()和executeBatch()方法进行批量处理的方法。此外,还讨论了如何通过配置rewriteBatchedStatements参数来提高批量操作的执行效率。

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

Connection connection = null;
try {

//获取Connection
connection = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ssm2.0?useUnicode=true", "root", "123456");
//connection = (Connection) getJdbcTemplate().getDataSource().getConnection();
//手动提交
connection.setAutoCommit(false);
PreparedStatement preparedStatement = null;

String sqlInsertBatch = "insert into user_opt (userName,optTime) values(?,?)";
preparedStatement = (PreparedStatement) connection.prepareStatement(sqlInsertBatch);

for(UserOpt userOpt:userOpts){
preparedStatement.setString(1, userOpt.getUserName());
preparedStatement.setDate(2, null);
preparedStatement.addBatch();
}
preparedStatement.executeBatch();

connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally{
connection.setAutoCommit(true);
if(connection != null){
connection.close();
}
}

ps:删除,更新和插入的形式是一样的。

         注意:1. 如果使用了 addBatch() -> executeBatch() 还是很慢,那就得使用到这个参数了

                      rewriteBatchedStatements=true (启动批处理操作)

                      在数据库连接URL后面加上这个参数:      

                          String dbUrl =  "jdbc:mysql://127.0.0.1:3306/ssm2.0?useUnicode=true& rewriteBatchedStatements=true";

                      2. 在代码中,pstmt的位置不能乱放,

                          //必须放在循环体外

                     preparedStatement = conn.prepareStatement("update content set introtext=? where id=?");

                     for(int i=0; i<10000; i++){

                           //放这里,批处理会执行不了,因为每次循环重新生成了pstmt,不是同一个了

                           //preparedStatement = conn.prepareStatement(sql);
                           preparedStatement .setString(1, "abc"+i);
                           preparedStatement .setInt(2, id);
                           preparedStatement .addBatch();//添加到同一个批处理中
                     }

                     preparedStatement .executeBatch();//执行批处理

转载于:https://www.cnblogs.com/krystal0901/p/5521446.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值