JDBC的批量操作
依次执行单条INSERT语句,效率低下。将SQL语句合成一个,能有效提高执行效率
案例:批量插入10万条数据
① 在URL尾部拼接?rewriteBatchedStatements=true
② SQL语句末尾不能用分号
③ 每次设置完参数,需要使用preparedStatement.addBatch()
来插入一行数据
④ 最后需要使用preparedStatement.executeBatch();
来执行语句
// 获取连接,并设置批量操作模式
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/wyt_test?rewriteBatchedStatements=true", "root", "123456");
// 编写SQL语句,末尾不能使用;
String SQL = "INSERT INTO t_employees(name, age, salary) VALUES(?,?,?)";
// 获取执行SQL语句的对象
PreparedStatement preparedStatement = connection.prepareStatement(SQL);
// 循环设置参数
for(int i = 0; i < 100000; i++) {
preparedStatement.setString(1, "wyt" + i);
preparedStatement.setInt(2, 1 + i);
preparedStatement.setDouble(3, 3000.00 + i);
// 批量设置参数
preparedStatement.addBatch();
}
// 执行语句
preparedStatement.executeBatch();
System.out.println("插入成功");
// 释放资源
preparedStatement.close();
connection.close();