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

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