MySQL的batch模式

MySQL的batch模式

MySQL的batch模式,其实也就是批处理模式。它比一条条插入的效率高多了。
这是从网上copy下来的例子:
首先使用普通的方式插入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);
    }
}

为啥效果差异会这么大呢?
首先得明确一个概念:
字符串解析是非常非常耗时的!!!正则表达式写几个了解一下(虽然数据库用的不仅仅是正则)。
所以SQL引擎的问题就来了,这里解析SQL语句如何更高效?答案是它使用了缓存,每个SQL生成查询计划后都会被缓存起来,下次来一个相同的SQL,不用解析,直接拿出查询计划。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值