【发布时间】: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} 上,行解释器抱怨说$res 是Not 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 的文档说,如果第一个参数未定义,您将获得一个数组引用数组。