How can I use a query with placeholder inside quotes? (perl / postgresql)

大憨熊 提交于 2019-11-29 14:15:45

You can't use placeholders inside quotes. You can use SQL string concatenation, but in this case, it's easier to do it by using multiplication:

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

That way, you don't have to append ' minutes' to the number when you execute the query.

I just found a solution here: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=321917

It works using ?::interval instead of 'interval ?':

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

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

or

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!