MySQL使用Batch批量处理

使用MySQL的Batch批量处理,
JDBC驱动版本需要5.1.13或以上
测试使用的JDBC驱动版本:mysql-connector-java-5.1.30-bin



测试表结构如下:
CREATE TABLE test (
  id int(11) DEFAULT NULL,
  name varchar(20) DEFAULT NULL
) ENGINE=InnoDB 

首先使用普通的方式插入100万条数据,使用时间81948毫秒
程序如下:

public class Test {
    public static void main(String[] args) throws ClassNotFoundException,
            SQLException {
        long start = System.currentTimeMillis();
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager
                .getConnection(
                        "jdbc:mysql://127.0.0.1:3306/xx",
                        "xx", "xx");

        connection.setAutoCommit(false);
        PreparedStatement cmd = connection
                .prepareStatement("insert into test values(?,?)");
        
        for (int i = 0; i < 1000000; i++) {
            cmd.setInt(1, i);
            cmd.setString(2, "test");
            cmd.executeUpdate();
        }
        connection.commit();
        
        cmd.close();
        connection.close();
        
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
使用批量处理,仅用7189毫秒,提升效果非常明显。
程序如下:

public class Test {
    public static void main(String[] args) throws ClassNotFoundException,
            SQLException {
        long start = System.currentTimeMillis();
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager
                .getConnection(
                        "jdbc:mysql://127.0.0.1:3306/xx?rewriteBatchedStatements=true",
                        "xx", "xx");

        connection.setAutoCommit(false);
        PreparedStatement cmd = connection
                .prepareStatement("insert into test values(?,?)");
        
        for (int i = 0; i < 1000000; i++) {
            cmd.setInt(1, i);
            cmd.setString(2, "test");
            cmd.addBatch();
            if(i%1000==0){
                cmd.executeBatch();
            }
        }
        cmd.executeBatch();
        connection.commit();
        
        cmd.close();
        connection.close();
        
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
与Oracle不同的是,需要添加下面的参数,才可以使用批量处理,否则还是使用逐条处理的方式。
rewriteBatchedStatements=true

开启MySQL的查询日志general_log,发现如下SQL
INSERT INTO test
VALUES (11, 'test'), (12, 'test'), (13, 'test')......


相对Oracle的批量处理,MySQL需要JDBC参数显式开启,并且对于JDBC驱动的版本也有要求。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29254281/viewspace-1151785/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29254281/viewspace-1151785/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值