2013-10-18 60 views
-3

我有這樣的代碼:perl DBI執行不識別'?'

if($update[$entity_id]) 
{ 
    my $sql = "UPDATE cache SET date = '?', value = '?' WHERE item_id = ? AND level = ? AND type = ?;"; 
} 
else 
{ 
    my $sql = "INSERT INTO cache (date, value, item_id, level, type) VALUES ('?','?',?,?,?);"; 
} 
my $db = $self->{dbh}->prepare(q{$sql}) or die ("unable to prepare"); 
$db->execute(time2str("%Y-%m-%d %X", time), $stored, $entity_id, 'entity', 'variance'); 

但是,當它要運行的更新我得到這個錯誤:

DBD::Pg::st execute failed : called with 5 bind variables when 0 are needed.

爲什麼?

+4

你真的想在每個'?'附近單引號嗎? $ stored變量中的 – toolic

+0

是文本,它可以包含空格,在日期中也有一個是需要的。 –

+4

不,你不需要它。這是佔位符的要點。 –

回答

6

如果你已經轉向了嚴格的和/或警告,你會看到你的問題是什麼。

你寫了

if (...) { 
    my $sql = ...; 
} else { 
    my $sql = ...; 
} 
execute($sql); 

這意味着您在if分支聲明$sql變量不在範圍和你要執行完全是空的SQL。

+1

當然,這是最大的問題。但所有的答案都很有幫助,謝謝大家 –

6

你正在準備字面'$sql',但那不是你唯一的問題,詞彙$sql變量超出{}以外的範圍。

嘗試,

use strict; 
use warnings; 
#... 

my $sql; 
if($update[$entity_id]) 
{ 
    $sql = "UPDATE cache SET date = ?, value = ? WHERE item_id = ? AND level = ? AND type = ?"; 
} 
else 
{ 
    $sql = "INSERT INTO cache (date, value, item_id, level, type) VALUES (?,?,?,?,?)"; 
} 
my $st = $self->{dbh}->prepare($sql) or die ("unable to prepare"); 
$st->execute(time2str("%Y-%m-%d %X", time), $stored, $entity_id, 'entity', 'variance');