mysql jdbc batch insert性能改善

原文参考https://stackoverflow.com/questions/2993251/jdbc-batch-insert-performance

问题描述:

当有数百万的数据需要insert的时候,如何改善性能呢?


   // Disable auto-commit
   connection.setAutoCommit(false);

   // Create a prepared statement
   String sql = "INSERT INTO mytable (xxx), VALUES(?)";
   PreparedStatement pstmt = connection.prepareStatement(sql);

   Object[] vals=set.toArray();
   for (int i=0; i<vals.length; i++) {
       pstmt.setString(1, vals[i].toString());
       pstmt.addBatch();
   }

   // Execute the batch
   int [] updateCounts = pstmt.executeBatch();
   System.out.append("inserted "+updateCounts.length);

通过使用batch以后,执行时间依然很长。

最佳答案:

mysql数据库通过设置参数rewriteBatchedStatements=true来达到目的。

jdbc:mysql://host:3306/db?rewriteBatchedStatements=true

原理

rewriteBatchedStatements=true是如何提升效率的呢?“It does so by rewriting of prepared statements for INSERT into multi-value inserts when executeBatch()”(Source)。这句话的意思是,当每次使用executeBatch() 的时候,不是发送n条insert到mysql。而是发送1条insert语句和多个值到mysql。

INSERT INTO X VALUES (A1,B1,C1)
INSERT INTO X VALUES (A2,B2,C2)
...
INSERT INTO X VALUES (An,Bn,Cn)

上述多条语句取而代之:

INSERT INTO X VALUES (A1,B1,C1),(A2,B2,C2),...,(An,Bn,Cn)

你可以设置mysql日志记录参数 (by SET global general_log = 1) ,来通过日志文件查看发送到mysql server的每一个sql语句。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值