使用PHP的大量SQLite插入

top*_*lch 5 php sqlite pdo

我有大约14000行逗号分隔值,我试图使用PHP PDO插入到sqlite表中,如下所示:

<?php
// create a PDO object
$dbh = new PDO('sqlite:mydb.sdb');

$lines = file('/csv/file.txt'); // import lines as array
foreach ($lines as $line) {
    $line_array = (','$line); // create an array of comma-separated values in each line
    $values = '';
    foreach ($line_array as $l) {
        $values .= "'$l', ";
    }
    substr($values,-2,0); // get rid of the last comma and whitespace
    $query = "insert into sqlite_table values ($values)"; // plug the value into a query statement
    $dbh->query($query); // run the query
}

?>
Run Code Online (Sandbox Code Playgroud)

这个查询需要很长时间,并且在没有中断的情况下运行它,我将不得不使用PHP-CLI.有更好(更快)的方法吗?

meo*_*ouw 22

通过将插入包装在单个事务中,您将看到良好的性能提升.如果不这样做,SQLite会将每个插入视为自己的事务.

<?php
// create a PDO object
$dbh = new PDO('sqlite:mydb.sdb');

// Start transaction
$dbh->beginTransaction();
$lines = file('/csv/file.txt'); // import lines as array
foreach ($lines as $line) {
    $line_array = (','$line); // create an array of comma-separated values in each line
    $values = '';
    foreach ($line_array as $l) {
        $values .= "'$l', ";
    }
    substr($values,-2,0); // get rid of the last comma and whitespace
    $query = "insert into sqlite_table values ($values)"; // plug the value into a query statement
    $dbh->query($query); // run the query
}
// commit transaction
$dbh->commit();

?>
Run Code Online (Sandbox Code Playgroud)

  • 这对我来说效果很好。我对它导入所有内容的速度感到惊讶。谢谢。 (2认同)
  • 为了获得更快的速度,将语句准备与事务结合使用。在可能影响实际查询的值的情况下,也使事情变得更安全,比如有意外的引号。 (2认同)