zoukankan      html  css  js  c++  java
  • 【java】[sql]使用Java程序向MySql数据库插入一千万条记录,各种方式的比较,最后发现insert批量插入方式对效率提升最明显

    我的数据库环境是mysql Ver 14.14 Distrib 5.6.45, for Linux (x86_64) using EditLine wrapper

    这个数据库是安装在T440p的虚拟机上的,操作系统为CentOs6.5.

    我的数据表是这样的:

    CREATE TABLE `emp` (
      `Id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) DEFAULT NULL,
      `age` smallint(3) DEFAULT NULL,
      `cdate` timestamp NULL DEFAULT NULL COMMENT 'createtime',
      PRIMARY KEY (`Id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=13548008 DEFAULT CHARSET=utf8;

     insert批量插入就是以下面这种方式写SQL语句

    insert into emp(name,age,cdate) 

    values

    ('A' , 20, '2019-10-13 00:00:00'),

    ('B' , 21, '2019-10-13 01:00:00'),

    ('C' , 22, '2019-10-13 05:00:00')

    对比表格如下

    序号 测试链接 用时 采用类库 sql写法 提交方式 stmt/pstmt   
    1 https://www.cnblogs.com/xiandedanteng/p/11666614.html 4m55s Spring JDBC Template insert into emp(name,age,cdate)values('','',''),('','',''),('','',''),('','',''),('','','') stmt.execute(sql)  stmt  
    2 https://www.cnblogs.com/xiandedanteng/p/11661796.html 5m MyBatis MyBatis batch Insert,具体实现估计就是上面的方式 估计为stmt.execute(sql),因为sql长度可调整   stmt  
    3 https://www.cnblogs.com/xiandedanteng/p/11666614.html 4m49s Spring JDBC Template insert into emp(name,age,cdate)values('','',''),('','',''),('','',''),('','',''),('','','')
    stmt.executeBatch();
     stmt  
    4 https://www.cnblogs.com/xiandedanteng/p/11666521.html 32m47s Spring JDBC Template insert into emp(name,age,cdate)values('','','')
    pstmt.executeBatch()
     prepared stmt  
    5 https://www.cnblogs.com/xiandedanteng/p/11666169.html 40m24s Spring JDBC Template insert into emp(name,age,cdate)values('','','')
     stmt.executeBatch();
      stmt  
    6 https://www.cnblogs.com/xiandedanteng/p/11663673.html  1h16m30s  MyBatis  insert into emp(name,age,cdate)values('','','')  估计为pstmt.execute(sql)  prepared stmt  

    其它测试都在2019.10.12,2019.10.13的随笔中,请各位按日期查看。

    最后可以得出结论如下:

    提升插入记录效率最明显的,是采用一次插入多条这种方式,如#1,#2,#3所做的,它相对于单条插这种方式有数量级的提升,用时基本控制在五分钟左右。

    至于其它如用executeBatch替换execute,用prepareStatement替换statement等,基本提升很小,几乎可以忽略不计

    理由可以这样想,DB的实际处理能力是很强大的,一次插多条和一次插一条IO开销差不多,但前者明显充分调动了DB的处理能力,后者只动员了很少部分,相对于IO开销来说挺不值得,一累计差别就明显了。

    以上测试所使用的程序都在 https://files.cnblogs.com/files/xiandedanteng/InsertMillionComparison20191013.rar 请各位自行下载。

    欢迎各位网友自行测试并评判。

    --END--2019年10月13日15:40:15

  • 相关阅读:
    第25周三
    第25周二
    第25周一
    第24周日
    第24周六
    第24周五
    第24周四经验感受想法
    第24周三
    第24周二
    01背包问题
  • 原文地址:https://www.cnblogs.com/heyang78/p/11666743.html
Copyright © 2011-2022 走看看