批量数据插入性能提升

功能实现:

1、url路径后面添加?rewriteBatchedStatements=true允许批量插入

2、insert into语句必须使用values,语句后面不能添加;结束

3、遍历添加完毕以后,统一批量执行 executeBatch( )

4、语句不能直接执行,每次需要装货,addBath( )最后executeBatch( );

@Test
  public void testInsert() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.cj.jdbc.Driver");

    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/book?rewriteBatchedStatement=true&user=root&password=123456");

    String sql = "insert into t_user (username,password,email) values (?,?,?)";

    PreparedStatement preparedStatement = connection.prepareStatement(sql);
//普通版
//String sql = "insert into t_user (username,password,email) values (?,?,?);";
//    long start = System.currentTimeMillis();
//    for (int i = 0; i < 10000; i++) {
//      preparedStatement.setString(1,"feifeid"+i+"号");
//      preparedStatement.setString(2,"feifei");
//      preparedStatement.setString(3, "feifei@qq.com");
//      preparedStatement.executeUpdate();
//    }
//    long end = System.currentTimeMillis();
//    System.out.println("执行10000次插入数据消耗的时间"+ (end - start));

    //升级版
    long start = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++) {
      preparedStatement.setString(1,"feifeii"+i+"号");
      preparedStatement.setString(2,"feifei");
      preparedStatement.setString(3, "feifei@qq.com");
      preparedStatement.addBatch();//不执行,追到values后面
      //因为SQL语句可以写成insert into t_user (username,password,email) values (?,?,?),(),()
    }
    preparedStatement.executeBatch();
    long end = System.currentTimeMillis();
    System.out.println("执行10000次插入数据消耗的时间"+ (end - start));

    preparedStatement.close();
    connection.close();

  }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值