在 Perl 中将 MySQL 结果作为哈希表返回

发布于 2024-12-10 02:49:20 字数 844 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无力看清 2024-12-17 02:49:20
while (my $result = $statement->fetchrow_hashref) {
        print $result->{id};
        print $result->{title};
        print $result->{price};
}

使用 fetchrow_hashref 将结果直接存储在哈希中

while (my $result = $statement->fetchrow_hashref) {
        print $result->{id};
        print $result->{title};
        print $result->{price};
}

Use fetchrow_hashref to have the result directly in a hash

家住魔仙堡 2024-12-17 02:49:20

有关 selectall_arrayref 的用法,请参阅 DBI 文档:

 $rows = $dbh->selectall_arrayref($query, {Slice=>{}}, @params)

$rows 是一个哈希数组。

Consult the DBI documentation for this use of selectall_arrayref:

 $rows = $dbh->selectall_arrayref($query, {Slice=>{}}, @params)

$rows is an Array of Hashes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文