java批处理sql
- 需要5.1.37及之后的驱动jar包
- 需要rewriteBatchedStatements=true
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Demo {
public static void main(String[] args) throws Exception {
// 实现批处理
// 需要5.1.37及之后的驱动jar包
// 需要rewriteBatchedStatements=true
String url = "jdbc:mysql://localhost:3306/demo1?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false&rewriteBatchedStatements=true";
String username = "root";
String password = "coderDreams";
Class.forName("com.mysql.jdbc.Driver");
String sql = "Insert into demo1 (`user`) values (?)";
Connection connection = DriverManager.getConnection(url, username, password);
// 开启事务
connection.setAutoCommit(false);
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 插入1000条
for (int i = 1; i <= 1000; ++i) {
preparedStatement.setObject(1,"name_"+i);
// 存
preparedStatement.addBatch();
// 每50次用掉
if (i % 50 == 0) {
// 用
preparedStatement.executeBatch();
// 清了重新存
preparedStatement.clearBatch();
}
}
// 最后统一提交
connection.commit();
}
}