2014-04-01 21 views
0

插入特殊chracters到MySQL您好,我是很新的perl的.. 我有這樣用perl

Id Comments 
-------------------------------- 
1  this is a 'comment' 
2  special comment 
3  user comment 'user' 
----------------------------------- 


    open (MYFILE, 'temp_data.txt'); 
while (<MYFILE>) { 
if($_=~/^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)/) 
{ 
    $id=$1;  
    $comment = $2; 
} 

while(<MYFILE>) 
{ 
    $line=$_; 
    if($line=~/^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)/) 
    { 
     seek(MYFILE, -length($_), 1); 
     last; 
} 
    else 
    {   if($_=~/\s*(.*)/) 
     { 
      $comment .=$1; 

     } 
    } 
} 

my $queryString = "INSERT INTO Headline (id,comment) VALUES ('$id', ' $comment')"; 

$sth = $dbh->prepare($queryString); 
$sth->execute() or die $DBI::errstr; 
$sth->finish(); 
} 

一個temp_data.txt文件,但同時插入到數據庫中,如果遇到特殊字符扔像這樣的錯誤。

DBD::mysql::st execute failed: 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 'comment')' at line 1 at head.pl line 1. 

任何人都可以幫助我嗎? 在此先感謝

回答

1

也許,您插入的數據有特殊符號。使用參數化查詢(它會保護您免受SQL注入):

my $queryString = "INSERT INTO Headline (id,comment) VALUES (?, ?)"; 

$sth = $dbh->prepare($queryString); 
$sth->execute($id, $comment) or die $DBI::errstr; 
$sth->finish();