2012-12-28 61 views
0
#!/usr/bin/perl 

use DBI;  

$fund=103; 
$mobile_number1="7700009896"; 
$city_address="hello word"; 

$sql_query3=(qq{ exec "INSERT INTO [192.168.14.28].CommunicationLog.dbo.sms_processedfeeds (pf_Fund,pf_trtype,pf_acno,pf_ihno,pf_Mobile,pf_msgtrtype,pf_msg,pf_entdt) VALUES ($fund,'CALL',0,NULL,'$mobile_number1','CALL','$city_address',Getdate())"}); 

my $sql_sms = $dbh->prepare($sql_query3); 
$sql_sms->execute(); 

,我发现了以下错误:我无法在perl脚本中执行插入命令吗?

DBD::ODBC::db prepare failed: [unixODBC][FreeTDS][SQL Server]The identifier that starts with 'INSERT INTO [192.168.14.28].CommunicationLog.dbo.sms_processedfeeds (pf_Fund,pf_trtype,pf_acno,pf_ihno,pf_Mobile,pf_msgtrtype,pf' is too long. Maximum length is 128. (SQL-42000) 
[unixODBC][FreeTDS][SQL Server]Statement(s) could not be prepared. (SQL-42000) at Mobile_verification.pl line 8. 
Can't call method "execute" on an undefined value at Mobile_verification.pl line 9. 
+0

我不知道'exec',但消息说第一个参数应该是一个标识符,而不是SQL查询。 – ikegami

回答

1

我不熟悉exec,但有消息称,第一个参数应该是一个标识符,而不是SQL查询。如果您打算使用exec SQL命令,则会滥用它。

但是你说你想要执行一个INSERT,所以也许你根本不打算使用EXECUTE。一个INSERT会是什么样子:

my $stmt = " 
    INSERT INTO [192.168.14.28].CommunicationLog.dbo.sms_processedfeeds (
       pf_Fund, 
       pf_trtype, 
       pf_acno, 
       pf_ihno, 
       pf_Mobile, 
       pf_msgtrtype, 
       pf_msg, 
       pf_entdt 
      ) VALUES (
       ?,?,?,?,?,?,?,Getdate() 
      ) 
"; 
my $sth = dbh->prepare($stmt); 
$sth->execute(
    $fund, 
    'CALL', 
    0, 
    undef, 
    '$mobile_number1', 
    'CALL', 
    $city_address, 
); 

注意:您可以用$dbh->do($stmt, undef, ...data...);

注意更换prepare + execute:我假设[192.168.14.28].CommunicationLog.dbo.sms_processedfeeds是一个有效的表标识。

3

你不需要exec并在声明中嵌套引号。使用这个代替

my $mobile_number1_lit = $dbh->quote($mobile_number1); 
my $city_address_lit = $dbh->quote($city_address); 
$sql_query3 = <<END_SQL; 
INSERT INTO [192.168.14.28].CommunicationLog.dbo.sms_processedfeeds (pf_Fund, pf_trtype, pf_acno, pf_ihno, pf_Mobile, pf_msgtrtype, pf_msg, pf_entdt) 
VALUES ($fund, 'CALL', 0, NULL, $mobile_number1_lit, 'CALL', $city_address_lit, Getdate()) 
END_SQL 

my $sql_sms = $dbh->prepare($sql_query3); 
$sql_sms->execute; 

或者最好使用占位符在prepare和参数传递给execute,这样

$sql_query3 = <<'END_SQL'; 
INSERT INTO [192.168.14.28].CommunicationLog.dbo.sms_processedfeeds (pf_Fund, pf_trtype, pf_acno, pf_ihno, pf_Mobile, pf_msgtrtype, pf_msg, pf_entdt) 
VALUES (?, 'CALL', 0, NULL, ?, 'CALL', ?, Getdate()) 
END_SQL 

my $sql_sms = $dbh->prepare($sql_query3); 
$sql_sms->execute($fun, $mobile_number1, $city_address);