首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Perl:在Perl-Hash中存储Mysql-table中的列。

Perl:在Perl-Hash中存储Mysql-table中的列。
EN

Stack Overflow用户
提问于 2011-03-27 11:46:40
回答 3查看 1.5K关注 0票数 1

我对Mysql和Perl有问题。

我正在编写代码,并将TODO-列表保存在Mysql表中。

现在,在脚本的开头,我希望将TODO-List从Mysql加载到Perl Hash中,这样我就不会重读urls。

  • Mysql有以下结构:

表"todo“-唯一Id "todoid”-TODO-url "todourl“

  • Perl中的TODO散列如下所示:

i %todo =( );

$VAR1 = 'http://www.example.com/661/'

如何在todo散列中加载Mysql表的所有Urls?

EN

回答 3

Stack Overflow用户

发布于 2011-03-27 14:03:36

您可以像Alan建议的那样使用DBI,但是使用更少的代码:

代码语言:javascript
复制
$todo = $dbh->selectall_hashref('SELECT todoid, todourl FROM todo', 'todoid');

如您所见,我没有使用dbi准备、执行、提取和完成,因为selectall_hashref方法为我们完成了所有这些工作。

请参阅在线文档:http://search.cpan.org/~timb/DBI-1.616/DBI.pm#selectall_hashref

票数 3
EN

Stack Overflow用户

发布于 2011-03-27 13:15:13

使用DBI连接到数据库,准备查询,执行查询并获取结果:

代码语言:javascript
复制
#!/usr/bin/env perl

use strict;
use warnings;

use DBI;

my %db_config = (
    'database' => 'your_database_name',
    'hostname' => 'your_hostname',
    'port'     => 'your_port',
    'username' => 'your_username',
    'password' => 'your_password',
);
my $dbh = DBI->connect(
   "DBI:mysql:database=$db_config{database};host=$db_config{hostname};port=$db_config{port}",
    $db_config{'username'}, $db_config{'password'},
) or die DBI->errstr();
my $sth = $dbh->prepare('SELECT todoid, todourl FROM todo')
  or die DBI->errstr();
$sth->execute() or die DBI->errstr();

my %todo;
while ( my $row = $sth->fetchrow_hashref() ) {
    $todo{ $row->{'todourl'} } = $row->{'todoid'};
}
票数 1
EN

Stack Overflow用户

发布于 2011-03-27 13:56:57

Class::DBI将为您进行查询和转换。然而,我认为DBIx::Class现在更受欢迎。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5449005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档