我对Mysql和Perl有问题。
我正在编写代码,并将TODO-列表保存在Mysql表中。
现在,在脚本的开头,我希望将TODO-List从Mysql加载到Perl Hash中,这样我就不会重读urls。
表"todo“-唯一Id "todoid”-TODO-url "todourl“
i %todo =( );
$VAR1 = 'http://www.example.com/661/';
如何在todo散列中加载Mysql表的所有Urls?
发布于 2011-03-27 14:03:36
您可以像Alan建议的那样使用DBI,但是使用更少的代码:
$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
发布于 2011-03-27 13:15:13
使用DBI连接到数据库,准备查询,执行查询并获取结果:
#!/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'};
}发布于 2011-03-27 13:56:57
Class::DBI将为您进行查询和转换。然而,我认为DBIx::Class现在更受欢迎。
https://stackoverflow.com/questions/5449005
复制相似问题