如何对所有列使用 selectall-hashref
How to use selectall-hashref for all columns
我想使用 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 => '...' },
... ]
你想要的是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 "",
},
]
我想使用 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 => '...' },
... ]
你想要的是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 "",
},
]