【问题标题】:DBI convert fetched arrayref to hashDBI 将获取的 arrayref 转换为哈希
【发布时间】:2017-05-06 21:13:13
【问题描述】:

我正在尝试编写一个程序来获取一个大的 MySQL 表,重命名一些字段并将其写入 JSON。这是我现在所拥有的:

use strict;

use JSON;
use DBI;

# here goes some statement preparations and db initialization

my $rowcache;
my $max_rows       = 1000;
my $LIMIT_PER_FILE = 100000;

while ( my $res = shift( @$rowcache )
    || shift( @{ $rowcache = $sth->fetchall_arrayref( undef, $max_rows ) } ) ) {

    if ( $cnt % $LIMIT_PER_FILE == 0 ) {

        if ( $f ) {
            print "CLOSE $fname\n";
            close $f;
        }

        $filenum++;
        $fname = "$BASEDIR/export-$filenum.json";

        print "OPEN $fname\n";
        open $f, ">$fname";
    }

    $res->{some_field} = $res->{another_field}
    delete $res->{another_field}

    print $f $json->encode( $res ) . "\n";

    $cnt++;
}

我使用了数据库行缓存技术 Speeding up the DBI 一切似乎都很好。

我现在唯一的问题是在$res->{some_field} = $res->{another_field} 上,行解释器抱怨说$resNot a HASH reference

谁能指出我的错误?

【问题讨论】:

  • 您可以使用 mysql-shell-output-formats 直接获取json 格式的输出JSON Format Output
  • 或者使用这个DBIx::JSON
  • @martinclayton,我明白这一点,但似乎fetchall_hashref 没有任何包含批处理行数的签名。如果我错了,请纠正我。
  • @AbhiNickz,它真的是一个巨大的数据库表,超过 2 亿个条目。它是否提供了将数据分解成块的可能性?此外,我需要在获取(重命名等)之后进行一些处理......
  • 不是为第一个参数传入undef,而是传递一个空的哈希引用,然后你应该得到一个哈希引用数组的引用。即 fetchall_arrayref({}, $max_rows)。 fetchall_arrayref 的文档说,如果第一个参数未定义,您将获得一个数组引用数组。

标签: mysql perl dbi


【解决方案1】:

如果你想让fetchall_arrayref返回一个hashrefs数组,第一个参数应该是一个hashref。否则,将返回一个 arrayrefs 数组,导致“不是 HASH 引用”错误。因此,为了返回完整的行作为 hashref,只需传递一个空的哈希:

$rowcache = $sth->fetchall_arrayref({}, $max_rows)

【讨论】:

  • 感谢您的帮助,但现在由于某种原因它显示为Can't use an undefined value as an ARRAY reference...我错过了什么吗?
  • 只是猜测:似乎rowcache 应该初始化为某个值?
  • @mr.nothing 尝试用my $rowcache = [];初始化行缓存。
  • 不幸的是,没有运气。将尝试进一步调查。
  • @nwellnhof:使用未定义的标量作为数组引用将自动验证一个空的匿名数组并设置标量来引用它。不会引发错误。问题是fetchall_arrayref 在到达表格末尾时返回undef
猜你喜欢
  • 2019-10-27
  • 2019-05-23
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 2012-11-11
  • 1970-01-01
相关资源
最近更新 更多