功能实现:
1、url路径后面添加?rewriteBatchedStatements=true允许批量插入
2、insert into语句必须使用values,语句后面不能添加;结束
3、遍历添加完毕以后,统一批量执行 executeBatch( )
4、语句不能直接执行,每次需要装货,addBath( )最后executeBatch( );
@Test
public void testInsert() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/book?rewriteBatchedStatement=true&user=root&password=123456");
String sql = "insert into t_user (username,password,email) values (?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//普通版
//String sql = "insert into t_user (username,password,email) values (?,?,?);";
// long start = System.currentTimeMillis();
// for (int i = 0; i < 10000; i++) {
// preparedStatement.setString(1,"feifeid"+i+"号");
// preparedStatement.setString(2,"feifei");
// preparedStatement.setString(3, "feifei@qq.com");
// preparedStatement.executeUpdate();
// }
// long end = System.currentTimeMillis();
// System.out.println("执行10000次插入数据消耗的时间"+ (end - start));
//升级版
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
preparedStatement.setString(1,"feifeii"+i+"号");
preparedStatement.setString(2,"feifei");
preparedStatement.setString(3, "feifei@qq.com");
preparedStatement.addBatch();//不执行,追到values后面
//因为SQL语句可以写成insert into t_user (username,password,email) values (?,?,?),(),()
}
preparedStatement.executeBatch();
long end = System.currentTimeMillis();
System.out.println("执行10000次插入数据消耗的时间"+ (end - start));
preparedStatement.close();
connection.close();
}