我已經嘗試了3種不同的方法將多個(超過500)行插入到SQLite表中。直覺地,下面的方法3是最快的。我會假設方法2將是最快的,因爲它使用「準備好的」語句句柄。但我的第三種方法 - 一次插入500行(500顯然是SQLite允許的最大值) - 速度更快。DBD :: SQLite插入多行的最快方法
我錯過了什麼?我應該繼續採用500方法還是有另一種方法?
注意:下面的代碼不是我的實際代碼,我只是爲了示例目的而將其寫入,並沒有經過測試。
use strict;
use warnings;
use DBI;
my $dsn = "DBI:SQLite:dbname=db";
my $dbh = DBI->connect($dsn,"","");
open my $data_file,"<","data.txt"; # 3 integer fields per line
APPROACH_1:
while (<$data_file>) {
my @fields = split "\t";
my $insert = join ",", @fields;
$dbh->do("insert into table values ($insert)";
}
APPROACH_2:
my $sql = "insert into table values (?,?,?)";
my $sth = $dbh->prepare($sql);
while (<$data_file>) {
my @fields = split "\t";
$sth->execute(@fields);
}
APPROACH_3:
my @inserts;
while (<$data_file>) {
my @fields = split "\t";
my $insert = '('.join(",",@fields).')';
push @inserts, $insert;
if (@inserts == 500) {
my $insert_500 = join ",", @inserts;
$dbh->do("insert into table values $insert_500";
undef @inserts;
}
}
# insert leftovers
我並不驚訝你的結果。我沒有太多使用SQLite,但至少在MySQL中,超過幾行的批量插入比單獨插入每行要快得多。這是有道理的:每個插入都需要與數據庫交談,這與數據庫有一定的關聯。 – ThisSuitIsBlackNot
此外,對於更多的行,使用DBMS的本地導入功能導入CSV可能會更快(當插入>〜100行時,MySQL的'LOAD DATA INFILE'比我的特定應用程序的批量導入快得多)。 SQLite [有一個CSV導入命令](https://www.sqlite.org/cli.html#csv),但我不確定您是否可以通過DBI使用它。 – ThisSuitIsBlackNot