一.code
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class TestBatch {
@Test
public void test1()throws Exception{
//没有用批处理的功能
long start = System.currentTimeMillis();
//建立连接
String url = "jdbc:mysql://localhost:3306/jdbctest";
String user = "root";
String pwd = "123456";
Connection connection = DriverManager.getConnection(url, user, pwd);
//编写sql
String sql = "insert into t_department values(null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for(int i=1; i<=2000; i++){
preparedStatement.setObject(1, "模拟部门名称" + i );
preparedStatement.setObject(2, "模拟部门简介" + i );
preparedStatement.executeUpdate();
//执行2000遍
}
preparedStatement.close();
connection.close();
long end = System.currentTimeMillis();
System.out.println("耗时:" +(end-start));
//耗时:6554
}
@Test
public void test2()throws Exception{
//使用批处理功能
long start = System.currentTimeMillis();
/* MySQL服务器端,默认批处理功能没有开启。需要通过参数告知mysql服务器,开启批处理功能。
在url后面再加一个参数 rewriteBatchedStatements=true*/
//建立连接
String url = "jdbc:mysql://localhost:3306/jdbctest";
String pwd = "123456";
String user = "root";
Connection connection = DriverManager.getConnection(url, user, pwd);
//编写sql
String sql = "insert into t_department values(null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for(int i=2001; i<=4000; i++){
preparedStatement.setObject(1, "模拟部门名称a" + i );
preparedStatement.setObject(2, "模拟部门简介b" + i );
preparedStatement.addBatch();//先攒着
}
preparedStatement.executeBatch();//执行批处理功能
preparedStatement.close();
connection.close();
long end = System.currentTimeMillis();
System.out.println("耗时:" +(end-start));//耗时:729
}
}