批处理最重要的一条就是rewriteBatchedStatements=true
String url = "jdbc:mysql://127.0.0.1:3306/fzhl_?rewriteBatchedStatements=true";
首先是将处理的大量sql打包入
preparedStatement.addBatch();
这个方法放入想让其执行打包sql语句的位置
preparedStatement.executeBatch()
这个方法是清空打包的sql
preparedStatement.clearBatch();
以上不带任何参数
演示
public class Main1 {
public static void main(String[] args) throws Exception{
// 批量执行需要加入该条件
String url = "jdbc:mysql://127.0.0.1:3306/fzhl_?rewriteBatchedStatements=true";
String user = "root";
String pass = "root";
Connection connection = DriverManager.getConnection(url,user,pass);
String sql = "insert into fz03 values(null,null,?,null)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0;i<500;i++){
preparedStatement.setInt(1,i);
// 将其打包,最后同意执行
preparedStatement.addBatch();
// 每打包100条后就执行一次
if((i+1)%100 == 0){
System.out.println(preparedStatement.executeBatch());
// 执行完后清空 清除处理
preparedStatement.clearBatch();
}
}
connection.close();
preparedStatement.close();
}
}