1. 程式人生 > >mysql 批量插入與單條插入 的效率比較

mysql 批量插入與單條插入 的效率比較

dtd rop too lac int 技術 public urn 方法

1、數據插入性能(單個插入和批量插入)
[java] view plain copy 技術分享技術分享
  1. public class Test {
  2. private Long id;
  3. private String test;
  4. public Long getId() {
  5. return id;
  6. }
  7. public void setId(Long id) {
  8. this.id = id;
  9. }
  10. public String getTest() {
  11. return test;
  12. }
  13. public void setTest(String test) {
  14. this.test = test;
  15. }
  16. }

mapper.xml文件

[html] view plain copy 技術分享技術分享
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="com.astrospace.test.mapper.TestMapper" >
  4. <resultMap id="test" type="com.astrospace.test.dmo.Test" >
  5. <id property="id" column="ID"/>
  6. <result property="test" column="TEST" />
  7. </resultMap>
  8. <insert id="add" parameterType="com.astrospace.test.dmo.Test">
  9. INSERT INTO TEST(ID,TEST) VALUES(#{id},#{test});
  10. </insert>
  11. <insert id="batchAdd" parameterType="java.util.List">
  12. INSERT INTO TEST(ID,TEST)
  13. VALUES
  14. <foreach collection="list" item="item" index="index" separator="," >
  15. (#{item.id},#{item.test})
  16. </foreach>
  17. </insert>
  18. </mapper>

調用add和batchAdd方法即可。

不同數據量測試5次,結果如下:

單獨插入50000條數據平均耗時:233748ms
批量插入50000條數據平均耗時:2590ms
對比:效率差50倍
單獨插入10000條數據平均耗時:22036ms
批量插入10000條數據平均耗時:3330ms
對比:效率差6倍
單獨插入1000條數據平均耗時:3122ms
批量插入1000條數據平均耗時:374ms
對比:效率差8倍

數據越多,效率愈發明顯。

mysql 批量插入與單條插入 的效率比較