我应该限制或减少数据库查询吗?

发布于 2024-11-26 10:05:53 字数 331 浏览 0 评论 0原文

我正在创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我的奇迹 2024-12-03 10:05:53

是的,它是

<?php
$lines = file('file.txt');
$count = count($lines);
$i = 0;
$query = "INSERT INTO table VALUES ";
foreach($lines as $line){
    $i++;
    if ($count == $i) {
        $query .= "('".$line."')";
    }
    else{
        $query .= "('".$line."'),";
    }
}
echo $query;

http://sandbox.phpcode.eu/g/5ade4.php

这个将进行一次查询,这比一行一查询样式快数倍!

yes it is

<?php
$lines = file('file.txt');
$count = count($lines);
$i = 0;
$query = "INSERT INTO table VALUES ";
foreach($lines as $line){
    $i++;
    if ($count == $i) {
        $query .= "('".$line."')";
    }
    else{
        $query .= "('".$line."'),";
    }
}
echo $query;

http://sandbox.phpcode.eu/g/5ade4.php

this will make one single query, which is multiple faster than one-line-one-query style!

沦落红尘 2024-12-03 10:05:53

使用《高性能 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).

撞了怀 2024-12-03 10:05:53

我会在一次包含所有值的大型查询中完成此操作。不过,为了确定一点,请确保在之前运行 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 and COMMIT; 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文