第一次写博客,写的不好请多多包涵。欢迎评论
今天需要对mysql做一个批量插入的操作,使用的是原生的jdbc对mysql进行操作,大约插入20几万条数据,刚开始事务是自动提交的,插完数据大约用了4分钟,后来把事务改为手动提交,插完数据用了20秒,时间相缩短了十倍。
如果不设置手动提交事务,那么默认每条插入语句都是一个事务,每次都要提交事务。设置手动提交事务的话,可以在循环前开启事务,循环结束后再提交事务,只需要提交一次事务。
下面是代码
@Test
public 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();
connection.commit();//执行完后,手动提交事务
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();
}
}
}
}