我应该限制或减少数据库查询吗?
我正在创建一个 PHP 脚本,将文本文件中的一些数据导入 MySQL 数据库。这些文本文件非常大,平均一个文件有 10,000 行,每一行对应于我想要在数据库中添加的一个新项目。 (我不会经常导入文件)
我担心从文件中读取一行,然后连续执行 10,000 次 INSERT 查询可能会导致一些问题。我有更好的方法来做到这一点吗?我应该对所有 10,000 个值执行一次 INSERT 查询吗?或者那会同样糟糕吗?
也许我可以达到一种媒介,并一次执行 10 或 100 个条目之类的操作。事实上,我的问题是我不知道什么是好的做法。也许连续 10,000 个查询就可以了,我只是担心而已。
有什么建议吗?
I'm creating a PHP script that imports some data from text files into a MySQL database. These text files are pretty large, an average file will have 10,000 lines in it each of which corresponds to a new item I want in my database. (I won't be importing files very often)
I'm worried that reading a line from the file, and then doing a INSERT query, 10,000 times in a row might cause some issues. Is there a better way for me to do this? Should I perform one INSERT query with all 10,000 values? Or would that be just as bad?
Maybe I can reach a medium, and perform something like 10 or 100 entries at once. Really my problem is that I don't know what is good practice. Maybe 10,000 queries in a row is fine and I'm just worrying for nothing.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,它是
http://sandbox.phpcode.eu/g/5ade4.php
这个将进行一次查询,这比一行一查询样式快数倍!
yes it is
http://sandbox.phpcode.eu/g/5ade4.php
this will make one single query, which is multiple faster than one-line-one-query style!
使用《高性能 MySQL》作者建议的准备好的语句。它节省了大量时间(节省了浪费的协议和 SQL ASCII 代码)。
Use prepared statements, suggested by the authors of High Performance MySQL. It saves a lot of time (saves from wasteful protocol and SQL ASCII code).
我会在一次包含所有值的大型查询中完成此操作。不过,为了确定一点,请确保在之前运行
START TRANSACTION;
并在之后运行COMMIT;
,这样如果在查询执行期间出现问题(这可能是,因为它很可能会运行相当长的时间),数据库不会受到影响。I would do it in one large query with all the values at once. Just to be sure, though, make sure you run
START TRANSACTION;
before andCOMMIT;
afterwards, so that if something goes wrong during the execution of the query (which is possible, since it will most likely run for a fairly long time), the database will not be affected.