【问题标题】:localtimestamp is always returning the same valuelocaltimestamp 总是返回相同的值
【发布时间】:2011-11-27 14:01:54
【问题描述】:

我最近将一个 Perl 应用程序表单 Oracle 移植到 Postgres(我第一次使用 Postgres),我被一个小问题难住了,我可以将其简化为以下示例代码:

use strict;
use warnings;
use DBI;

my @db_params = qw (dbi:Pg:host=127.0.0.1;database=test test test);

my $dbh = DBI->connect(@db_params, {AutoCommit => 0 } ) or die ;
while (1) {
    my $sth = $dbh->prepare_cached('SELECT localtimestamp ') or die;
    $sth->execute() or die;
    my $result = $sth->fetchall_arrayref();
    print $result->[0][0] , "\n";
    sleep(5);
}

这个输出:

2011-11-27 16:46:25.94291
2011-11-27 16:46:25.94291
2011-11-27 16:46:25.94291

除非我断开连接并重新连接到数据库,否则我一直得到相同的时间戳。

如何确保每次从数据库中选择 localtimestamp 时,我得到的值与执行 sql 的时间相对应?

【问题讨论】:

    标签: perl postgresql dbi


    【解决方案1】:

    因为您没有使用自动提交,所以您始终处于同一个事务中,并且 localtimestamp 在 Postgres 中获取该事务开始时的时间戳。 IE。您需要使用$dbh->begin_work 和$dbh->commit 为您的查询创建单独的事务。

    【讨论】:

    • 你是对的!奇怪的是,我没有想到 Oracle 和 Pg 之间的事务工作方式不同。原始代码在 Oracle 中按预期工作,无需提交事务!
    • 是的,Oracle 的行为不同,但是如果您在一个事务中更改一堆行的时间戳,那么如果它们获得所有相同的时间戳对我来说更有意义。
    • 事务中发生的所有事情应该同时发生。 PostgreSQL 对事务中时间戳的处理逻辑上更准确。
    【解决方案2】:

    还可以查看manual 中的statement_timestamp 和clock_timestamp 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-22
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      相关资源
      最近更新 更多