gpt4 book ai didi

sql - 在 Perl 中的 PostgreSQL 中参数化时间戳引用的问题

转载 作者:行者123 更新时间:2023-11-29 12:31:24 26 4
gpt4 key购买 nike

我正在尝试在 Perl 脚本中使用参数化查询从 Postgres 数据库中获取一些时间戳。这是一个简单的示例,仅用于教学目的。

我已经将 $start_date$end_date 定义为时间戳和间隔:

my $start_date = "current_timestamp - interval '6 hours'";
my $end_date = "current_timestamp";

我使用以下内容提交到数据库,其中 $dbh 之前已定义:

my $sql = "SELECT cast(? as timestamp), cast(? as timestamp)";
my $sth = $dbh->prepare($sql);
$sth->execute($start_date, $end_date);

当我这样做时,我遇到了一个有点令人困惑的错误。

DBD::Pg::st execute failed: ERROR:  date/time value "current" is no longer supported

我知道 current 自 7.2 以来在 PG 中不再受支持,但我没有使用它。我正在使用 current_timestamp,这是 支持的,AFACT。也就是说,如果我输入 psql:

select (cast(current_timestamp - interval '6 hours' as timestamp), cast(current_timestamp as timestamp));

结果如我所料(两个时间戳,前者早于后者 6 小时)。

我也可以使用 now() 而不是 current_timestamp。我可以通过以下方式使用它:

my $start_date = "now() - interval '6 hours'"; 
my $end_date = "now()";

当我尝试在 perl 中运行查询时,出现以下错误:

DBD::Pg::st execute failed: ERROR:  invalid input syntax for type timestamp: "now() - interval '6 hours'"

然而,查询:

select (cast(now() - interval '6 hours' as timestamp), cast(now() as timestamp));

给我预期的结果。

我很困惑。

最佳答案

问题是 SQL 占位符不代表表达式,而是代表单个值。而且该值不能是函数。你可以这样做:

my $start_date = "6 hours";
my $sql = "SELECT current_timestamp - cast(? as interval), current_timestamp";
my $sth = $dbh->prepare($sql);
$sth->execute($start_date);

你在 Perl 中所做的等同于在 psql 中这样做:

select (cast('current_timestamp - interval ''6 hours''' as timestamp), cast('current_timestamp' as timestamp));

关于sql - 在 Perl 中的 PostgreSQL 中参数化时间戳引用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19434344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com