在 Perl 中将 MySQL 结果作为哈希表返回
在 Perl 中,我正在执行类似于以下的 SQL 查询:
SELECT `id`, `title`, `price` FROM `gamelist`
我想要做的是获取此查询的结果并将其转储到哈希表中。我正在使用 DBI,目前我只知道如何执行以下操作:
my %results;
my $count = 0;
while( @result = $statement->fetchrow() ){
%results{'id'}[$count] = $result[0];
%results{'title'}[$count] = $result[1];
%results{'price'}[$count] = $result[2];
$count++;
}
但是我不喜欢使用 $result[0]
并相信第一个字段将是 ID。我更愿意有这样的东西:
my %results;
my $count = 0;
while( %result = $statement->fetchrow_as_hashtable() ){
%results{'id'}[$count] = %result{'id'};
%results{'title'}[$count] = %result{'title'};
%results{'price'}[$count] = %result{'price'};
$count++;
}
我尝试在 Google 上查找,但找不到 DBI/Perl 中内置的许多好的答案。我确实找到了一个提供此功能的开源类,但我觉得这应该可以在不使用其他人的类的情况下实现。
In Perl I'm making an SQL query akin to the following:
SELECT `id`, `title`, `price` FROM `gamelist`
What I wish to do is take the result of this query and dump it into a hash table. I am using DBI and currently I only know how to do the following:
my %results;
my $count = 0;
while( @result = $statement->fetchrow() ){
%results{'id'}[$count] = $result[0];
%results{'title'}[$count] = $result[1];
%results{'price'}[$count] = $result[2];
$count++;
}
However I don't like using $result[0]
and trusting that the first field will be the ID. I would much rather have something like:
my %results;
my $count = 0;
while( %result = $statement->fetchrow_as_hashtable() ){
%results{'id'}[$count] = %result{'id'};
%results{'title'}[$count] = %result{'title'};
%results{'price'}[$count] = %result{'price'};
$count++;
}
I tried looking around on Google but couldn't find many good answers built into DBI/Perl. I did find an open-source class that offered this functionality, but I feel like this should be possible without the use of someone else's class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fetchrow_hashref
怎么样?What about
fetchrow_hashref
?使用 fetchrow_hashref 将结果直接存储在哈希中
Use fetchrow_hashref to have the result directly in a hash
有关
selectall_arrayref
的用法,请参阅DBI
文档:$rows
是一个哈希数组。Consult the
DBI
documentation for this use ofselectall_arrayref
:$rows
is an Array of Hashes.