一、JDBC中批处理SQL语句的介绍
二、使用批量处理和非批量处理,进行演示,看具体的耗时区别
public class Batch_ {
@Test
public void noBatch() throws Exception {
Connection connection = JDBCUtils.getConnection();
String sql = "INSERT INTO ADMIN2 VALUES(null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();//开始时间
for (int i = 0; i < 500; i++) {
preparedStatement.setString(1, "jack" + i);
preparedStatement.setString(2, "666");
preparedStatement.executeUpdate();
}
long end = System.currentTimeMillis(); //结束时间
System.out.println("传统的方式 耗时:" + (end - start));//传统的方式 耗时:53942毫秒
//关闭连接
JDBCUtils.close(null, preparedStatement, connection);
}
//使用批量方式添加数据
@Test
public void batch() throws Exception {
Connection connection = JDBCUtils.getConnection();
String sql = "INSERT INTO ADMIN2 VALUES(null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();//开始时间
for (int i = 0; i < 500; i++) {
preparedStatement.setString(1, "jack" + i);
preparedStatement.setString(2, "666");
//将sql语句加入到批处理包中->看源码
preparedStatement.addBatch();
if ((i + 1) % 1000 == 0) {
preparedStatement.executeBatch();
//清空一把
preparedStatement.clearBatch();
}
}
long end = System.currentTimeMillis(); //结束时间
System.out.println("批量的方式 耗时:" + (end - start));//批量的方式 耗时:4毫秒
//关闭连接
JDBCUtils.close(null, preparedStatement, connection);
}
}



