我想用selectall_hashref实现这个子例程。
sub query {
use SQL::Abstract;
my $sql = SQL::Abstract->new;
my ($table, $fields, $where) = @_;
my ($stmt, @bind) = $sql->select($table, $fields, $where);
my $sth = $dbh->prepare($stmt);
$sth->execute(@bind);
my @rows;
while(my @row = $sth->fetchrow_array() ) {
my %data;
@data{ @{$sth->{NAME}} } = @row;
push @rows, \%data;
}
return \@rows;
}不幸的是,selectall_hashref需要一个想要列的列表。有办法写类似我的第一个子程序吗?
显然,这是行不通的:
sub query {
return $dbh->selectall_hashref(shift, q/*/);
}预期的输出可以是哈希数组或散列哈希:
{ '1' => { column1 => 'foo', column2 => 'bar' },
'2' => { column1 => '...', column2 => '...' },
... } 或
[ { column1 => 'foo', column2 => 'bar' },
{ column1 => '...', column2 => '...' },
... ]发布于 2015-02-12 13:06:47
你想要的是selectall_arrayref,而不是selectall_hashref。正是这样做的。
use DBI;
use Data::Printer;
my $dbh = DBI->connect('DBI:mysql:database=foo;', 'foo', 'bar');
my $foo = $dbh->selectall_arrayref(
'select * from foo',
{ Slice => {} }
);
p $foo
__END__
\ [
[0] {
id 1,
baz "",
},
[1] {
id 2,
baz "",
},
]https://stackoverflow.com/questions/28477638
复制相似问题