Search code examples
databaseperlpostgresqldbddbd-pg

perl DBI execute doesn't recognize '?'


I have this code:

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');

But when it want to run the update I get this error:

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

Why?


Solution

  • If you had turned on strict and/or warnings, you would see what your problem is.

    You're writing

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

    Which means that the $sql variables that you declare in the if branches aren't in scope and you're trying to execute completely empty SQL.