简体   繁体   English

使用一条语句插入多行与在MySQL中批量插入

[英]Insert multiple rows using one statement vs batch insert in mysql

Which one will give me better performance? 哪一个会给我更好的表现?

  1. Use Java simply loop the value and added to the sql string and execute the statement at once? 使用Java只是将值循环并添加到sql字符串中,然后立即执行该语句? Note that PreparedStatement is also used. 请注意,还使用PreparedStatement。

    INSERT INTO tbl ( c1 , c2 , c3 ) VALUES ('r1c1', 'r1c2', 'r1c3'), ('r2c1', 'r2c2', 'r2c3'), ('r3c1', 'r3c2', 'r3c3')

  2. Use the batch execution as below. 如下使用批处理执行。

    String SQL_INSERT = "INSERT INTO tbl (c1, c2, c3) VALUES (?, ?, ?);";

     try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_INSERT); ) { int i = 0; for (Entity entity : entities) { statement.setString(1, entity.getSomeProperty()); // ... statement.addBatch(); i++; if (i % 1000 == 0 || i == entities.size()) { statement.executeBatch(); // Execute every 1000 items. } } } 

I did a presentation a few years ago I called Load Data Fast! 几年前,我做了一个演讲,我称之为快速加载数据! . I compared many different methods of inserting data as fast as possible, and benchmarked them. 我比较了许多不同的尽快插入数据的方法,并对它们进行了基准测试。

LOAD DATA INFILE was much faster than any other method. LOAD DATA INFILE比任何其他方法快得多。

But there are other factors that affect the speed, like the type of data, and the type of hardware, and perhaps the load on the system from other concurrent clients of the database. 但是还有其他影响速度的因素,例如数据类型和硬件类型,以及其他并发数据库客户端对系统的负载。 The results I got only describe what the performance is on a Macbook Pro. 我得到的结果仅描述了Macbook Pro的性能。

Ultimately, you need to test your specific case on your server to get the most accurate answer. 最终,您需要在服务器上测试您的特定情况以获得最准确的答案。

This is what being a software engineer is about. 这就是成为一名软件工程师的目的。 You don't always get the answers spoon-fed to you. 您并非总能得到汤匙喂给您的答案。 You have to do some testing to confirm them. 您必须进行一些测试以确认它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM