一、使用普通的方式插入10000条数据
@Test
public void testInsert() throws Exception {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/itcast?user=root&password=123456");
//3.编写sql语句
String sql = "insert into employee(name, salary, departmentId) values(?, ?, ?);";
//4.创建statement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//5.占位符赋值
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
preparedStatement.setObject(1, "dd" + i);
preparedStatement.setObject(2, 5);
preparedStatement.setObject(3, 2);
//6.发送sql语句,并且获取结果
preparedStatement.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println("执行100000次数据插入消耗的时间" + (end - start) + "ms");
//8.关闭资源
connection.close();
preparedStatement.close();
}
可以测出,一共用了14000多ms
二、使用批量插入的方式插入100000条数据
我们在执行insert语句的时候,其实可以一次携带多个值
insert into employee(name, salary, departmentId) values(?, ?, ?), (),()
代码示例
@Test
public void testBatchInsert() throws Exception {
// 1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 2.获取连接
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/itcast?rewriteBatchedStatements=true", "root", "123456");
// 3.编写sql语句
String sql = "insert into employee(name, salary, departmentId) values(?, ?, ?)";
// 4.创建statement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//5.占位符赋值
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
preparedStatement.setObject(1, "dd" + i);
preparedStatement.setObject(2, 5);
preparedStatement.setObject(3, 2);
// preparedStatement.executeUpdate();
preparedStatement.addBatch();// 不执行,追加到values后面!
}
preparedStatement.executeBatch();// 执行批量操作!
// 这里可能会有另外的一个方法:statement.executeLargeBatch(); //这个方法是假的,jdbc里面没有任何操作!!
long end = System.currentTimeMillis();
System.out.println("执行100000次数据插入消耗的时间" + (end - start) + "ms");
//8.关闭资源
connection.close();
preparedStatement.close();
}
结果为:254ms,可以发现明显优化了很多
三、总结
1.url路径后面添加 ?rewriteBatchedStatements=true 允许批量插入
2.insert into 必须写values, 语句末尾 不能 添加 “;” 结束,因为它是采用追加的方式接上SQL语句的
3.不是执行语句每条,是批量添加 addBatch();
4.遍历添加完毕以后,统一批量执行 executeBatch()
如下图可以看见 executeLargeBatch方法
中并没有执行任何操作,因此它其实是一个假方法