mysql使用jdbc进行批量插入时把事务设为手动提交比事务自动提交速度快了10倍

第一次写博客,写的不好请多多包涵。欢迎评论

今天需要对mysql做一个批量插入的操作,使用的是原生的jdbc对mysql进行操作,大约插入20几万条数据,刚开始事务是自动提交的,插完数据大约用了4分钟,后来把事务改为手动提交,插完数据用了20秒,时间相缩短了十倍。

          如果不设置手动提交事务,那么默认每条插入语句都是一个事务,每次都要提交事务。设置手动提交事务的话,可以在循环前开启事务,循环结束后再提交事务,只需要提交一次事务。

 

下面是代码
@Test
public void getModelDetailLogV2(){
   /*数据源*/
    List all = modelShowLDetailLogV2Service.findAll();
    Connection connection = null;
    try {
        // 1.加载MySQL的驱动
        Class.forName("com.mysql.jdbc.Driver"); 
        /*连接数据库的参数*/
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/log_repeat", "root", "root");
       /*插入的sql*/
        String sql="INSERT into modelshowdetaillogv2(id,showId,email,browserTime,time,result,\n" +
                "platform,tipAmount,detail,modelShowId,logNo,logType,timeDate,customerName) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        connection.setAutoCommit(false);//将自动提交关闭,开启手动提交
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        long start=System.currentTimeMillis();
       /*循环插入*/
        for (int i=0;i

 

你可能感兴趣的:(jdbc)