mysql 批量插入优化

首先在资源文件jdbc.properties文件中url后添加:  ?rewriteBatchedStatements=true 功能为允许MySQL批量插入

 

测试方法:

@Test
public void testInsert3() throws SQLException {
    ConnectionClass connectionClass = new ConnectionClass();
    Connection connection = connectionClass.getConnection();
    //设置不允许自动提交数据,因为提交数据也会耗费时间,等到最后sql缓存完了一次性提交
    connection.setAutoCommit(false);
    String sql = "insert into goods(name) values(?)";
    /*预编译sql,会被缓存下来,以后每次使用编译后的sql,减少重复编译的时间 比statement快速*/
    PreparedStatement preparedStatement =
            connection.prepareStatement(sql);

    long start = System.currentTimeMillis();
    for(int i = 1;i<=1000000;i++){
        preparedStatement.setObject(1,"name_"+i);
        preparedStatement.addBatch();
        if(i % 500 == 0){
            /*缓存sql语句,攒到一定量的sql才提交*/
            /*最开始为每一句sql都提交一次 非常耗费时间*/
            preparedStatement.executeBatch();
            preparedStatement.clearBatch();
        }
    }
    /*缓存完了再统一提交*/
    connection.commit();
    long end = System.currentTimeMillis();
    System.out.println(end - start);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值