perl DBI execute 无法识别"?"



我有这个代码:

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::P g::st 执行失败:当需要 0 个绑定变量时,使用 5 个绑定变量调用。

为什么?

如果您打开了严格和/或警告,您将看到问题所在。

你在写

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

这意味着您在if分支中声明的$sql变量不在范围内,并且您正在尝试执行完全空的 SQL。

您正在准备文字'$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');

最新更新