失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > mysql使用jdbc进行批量插入时把事务设为手动提交比事务自动提交速度快了10倍

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

时间:2020-08-09 04:34:25

相关推荐

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

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

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

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

下面是代码

@Testpublic void getModelDetailLogV2(){/*数据源*/List<ModelShowDetailLogV2> 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<all.size();i++){preparedStatement.setString(1,all.get(i).getId());preparedStatement.setString(2,all.get(i).getShowId());preparedStatement.setString(3,all.get(i).getEmail());preparedStatement.setLong(4,all.get(i).getBrowserTime());preparedStatement.setLong(5,all.get(i).getTime());preparedStatement.setInt(6,all.get(i).getResult());preparedStatement.setString(7,all.get(i).getPlatform());preparedStatement.setInt(8,all.get(i).getTipAmount());preparedStatement.setString(9,all.get(i).getDetail());preparedStatement.setString(10,all.get(i).getModelShowId());preparedStatement.setString(11,all.get(i).getLogNo());preparedStatement.setString(12,all.get(i).getLogType());preparedStatement.setLong(13,all.get(i).getTimeDate());preparedStatement.setString(14,all.get(i).getCustomerName());preparedStatement.addBatch();//把数据放入缓存区if(i%10000==0){//刷新缓存区preparedStatement.executeBatch();preparedStatement.clearBatch();//清除之前的数据}}//刷新缓存区preparedStatement.executeBatch();preparedStatement.close();mit();//执行完后,手动提交事务connection.setAutoCommit(true);//在把自动提交打开System.out.println("插入完成");long end=System.currentTimeMillis();System.out.println("花费时间:"+(end-start));} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}finally{if(connection != null){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}}

如果觉得《mysql使用jdbc进行批量插入时把事务设为手动提交比事务自动提交速度快了10倍》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。