2015-08-27 194 views
0

我有一堆由'\n'以* .txt文件分隔的DOI。我寫的perl腳本應該讀取文件的每一行並執行選擇查詢。但是,該程序無法執行SQL查詢。你能幫我解決這個問題嗎?無法執行SQL查詢

執行後,我收到以下錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' http://dx.doi.org/10.1002/1521-3757(20001103)112:21 <3947::aid-ange3947>3.0'

的dois.txt文件的第一行包含以下DOI:

`http://dx.doi.org/10.1002/1521-3757(20001103)112:21<3947::aid-ange3947>3.0.co;2-k` 

這裏是我的代碼:

my $file = 'dois.txt'; 

open(my $fh, '<:encoding(UTF-8)', $file) 
    or die " Could not open file $file"; 
while (my $doi = <$fh>) { 

chomp($doi); 
my $sth = $dbh->prepare("select * from mytable where doi = ''$doi'';"); 
$sth->execute || die "failed to execute:\n ", $DBI::Errstr; 
print $sth->fetchrow_array, "\n"; 

} 
close FH; 
$dbh->disconnect; 
+0

創建一個字符串並從''select * from mytable doi =''$ doi'';'' – Drew

回答

2

您想在循環外調用prepare,以便執行計劃只需計算結束一次(即更快)。此外,除了僅準備一次查詢外,如果您使用placeholders/bind parameters,則無需正確指出如何正確引用值。

my $file = 'dois.txt'; 

open(my $fh, '<:encoding(UTF-8)', $file) or die "Could not open file $file: $!\n"; 
my $sth = $dbh->prepare(q{select * from mytable where doi = ?}); 

while (my $doi = <$fh>) { 
    chomp($doi);  
    $sth->execute($doi) || die "failed to execute:\n ", $DBI::Errstr; 
    print $sth->fetchrow_array, "\n"; 
} 

close $fh; 
$dbh->disconnect;