【问题标题】:How to walk through a large result set with perl and postgresql如何使用 perl 和 postgresql 遍历大型结果集
【发布时间】:2019-05-18 03:00:53
【问题描述】:

Perl 的DBD::Pg PostgreSQL 绑定将始终获取查询的整个结果集。因此,如果您使用简单的准备执行来遍历一个大表,您只需运行$sth->execute() 就可以将整个表保存在内存中。准备好的语句和像fetch_row 这样的调用没有帮助。

如果您使用的是 BIG 表,以下操作将会失败。

use DBI;
my $dbh =   DBI->connect("dbi:Pg:dbname=big_db","user","password",{
        AutoCommit => 0,
        ReadOnly => 1,
        PrintError => 1,
        RaiseError =>  1,
});

my $sth = $dbh->prepare('SELECT * FROM big_table');
$sth->execute(); #prepare to run out of memory here
while (my $row = $sth->fetchrow_hashref('NAME_lc')){
  # do something with the $row hash
}
$dbh->disconnect();

【问题讨论】:

    标签: postgresql perl large-data dbi database-cursor


    【解决方案1】:

    要解决此问题,请声明一个游标。然后使用游标获取数据块。 ReadOnly 和 AutoCommit 设置对于此工作很重要。因为 PostgreSQL 只会做 CURSORS 读取。

    use DBI;
    my $dbh =   DBI->connect("dbi:Pg:dbname=big_db","user","password",{
            AutoCommit => 0,
            ReadOnly => 1,
            PrintError => 1,
            RaiseError =>  1,
    });
    
    $dbh->do(<<'SQL');
    DECLARE mycursor CURSOR FOR
    SELECT * FROM big_table
    SQL
    
    my $sth = $dbh->prepare("FETCH 1000 FROM mycursor");
    while (1) {
      warn "* fetching 1000 rows\n";
      $sth->execute();
      last if $sth->rows == 0;
      while (my $row = $sth->fetchrow_hashref('NAME_lc')){
        # do something with the $row hash
      }
    }
    $dbh->disconnect();
    

    【讨论】:

    • 应该没有必要在循环内不断地重新创建语句句柄。进行该更改有助于其他优化,例如将 fetchrow_hashref 替换为循环外的一个 bind_colums 调用,然后在内部进行简单的 fetch,这会更快。
    猜你喜欢
    • 2020-07-12
    • 2012-06-05
    • 2015-12-16
    • 2011-11-30
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多