[英]What would be the best approach of adding 100,000+ records to a MySQL database via PHP?
I'm developing an application and have over 100,000 records, that have been read in from a file, which need to be inserted into a MySQL database. 我正在开发一个应用程序并拥有超过100,000条记录,这些记录已经从一个文件读入,需要插入到MySQL数据库中。
What would be the best approach of inserting these to the database? 将这些插入数据库的最佳方法是什么?
The approach I'm currently working from is generating a SQL query to insert all the records in one call to the database. 我目前正在使用的方法是生成一个SQL查询,以便在对数据库的一次调用中插入所有记录。
INSERT INTO table (field1, field2)
VALUES
(123, 456),
(125, 984),
...
Is there a limit to the number of records that can be inserted at once? 可以一次插入的记录数量是否有限制? And in terms of performance is this the best method? 而在性能方面这是最好的方法吗?
I have considered an alternative of splitting the records into a number of queries but I'm unsure if this would have any benefit? 我已经考虑过将记录拆分成多个查询的替代方案,但我不确定这是否有任何好处?
Any advice would be greatly appreciated, thanks! 任何建议将不胜感激,谢谢!
The way you're doing it is indeed very efficient. 你这样做的方式确实非常有效。 The maximum query length is determined by the max_allowed_packet setting so you may need to split the query into several queries, see http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_max_allowed_packet 最大查询长度由max_allowed_packet设置决定,因此您可能需要将查询拆分为多个查询,请参阅http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_max_allowed_packet
I would recommend adding one row at a time with LOW_PRIORITY
or DELAYED
depending on your engine. 我建议使用LOW_PRIORITY
或DELAYED
一次添加一行,具体取决于您的引擎。 The reason for this is that other users of your table will still have access to read and write once in a while instead of having the entire table locked for an extended period of time. 原因是您的表的其他用户仍然可以偶尔读取和写入一次,而不是让整个表长时间锁定。
Permissions and/or format not withstanding, using 权限和/或格式不承受,使用
load data infile to import the file directly 加载数据infile直接导入文件
LOAD DATA INFILE is probably the best way to go. LOAD DATA INFILE可能是最好的方式。 Especially if the data file you're reading from is already in a format that can be used by it. 特别是如果您正在读取的数据文件已经是可以由其使用的格式。
您也可以考虑使用MySQL的LOAD DATA INFILE命令从CSV文件中插入数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.