我想使用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 => '...' },
... ]
答案 0 :(得分:3)
您想要的是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 "",
},
]