如何在带引号的占位符中使用查询? (perl / postgresql)

时间:2012-05-18 21:04:14

标签: perl postgresql dbi

我试图执行以下脚本:

#!/usr/bin/perl -w

use strict;
use DBI;

my $db = "Pg";
my $db_database = "whatever";
my $user = "whatever";
my $password = "whatever";

my $dbh = DBI->connect("dbi:$db:dbname=$db_database", $user, $password);

my $query = $dbh->prepare (q{SELECT
                   arrival_date - INTERVAL '? MINUTE'
                   FROM emails LIMIT 1})
  or die ("unable to prepare");
$query->execute(60) or die("unable to execute");

print $query->fetchrow_array, "\n";

(arrival_date具有以下格式:带时区的时间戳NOT NULL默认值CURRENT_TIMESTAMP)

问题是未检测到问号占位符,因为其内部单引号:

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

如果我使用qq {},$ 1占位符,并使用$ dbh-> quote尝试了一些变体,则无效。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:10)

您不能在引号内使用占位符。您可以使用SQL字符串连接,但在这种情况下,使用乘法更容易实现:

my $query = $dbh->prepare (q{SELECT
                   arrival_date - ? * INTERVAL '1 MINUTE'
                   FROM emails LIMIT 1});
$query->execute(60);

这样,您在执行查询时不必将' minutes'附加到该号码。

答案 1 :(得分:3)

我刚刚在这里找到了一个解决方案:http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=321917

使用?:: interval而不是'interval?':

my $query = $dbh->prepare (q{SELECT
                   arrival_date - ?::interval
                   FROM emails LIMIT 1});

$query->execute('60 MINUTE');

答案 2 :(得分:2)

my $query = $dbh->prepare (<<SQL) or die ("unable to prepare");
SELECT arrival_date - INTERVAL ? FROM emails LIMIT 1
SQL
$query->execute("60 MINUTE");

my $query = $dbh->prepare (<<SQL) or die ("unable to prepare");
SELECT arrival_date - INTERVAL CONCAT(?, " MINUTE") FROM emails LIMIT 1
SQL
$query->execute(60);