【问题标题】:Perl: Store column from Mysql-table in Perl-HashPerl:将 Mysql 表中的列存储在 Perl-Hash 中
【发布时间】:2011-07-23 20:52:13
【问题描述】:

我在使用 Mysql 和 Perl 时遇到问题。

我正在编写一个 Web-Crawler 并且我正在将 TODO-List 保存在一个 Mysql 表中。

现在,在脚本的开头,我想将 Mysql 中的 TODO-List 加载到 Perl 哈希中,这样我就不会重新抓取 url。

  • Mysql 有以下 结构:

表“todo” - 唯一 ID “todo” - TODO-urls“todourl”

  • Perl 中的 TODO Hash 是这样的:

我的 %todo = ( );

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

如何在我的 todo hash 中加载 Mysql 表的所有 Url?

【问题讨论】:

    标签: mysql perl hash


    【解决方案1】:

    您可以像 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

    【讨论】:

      【解决方案2】:

      使用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'};
      }
      

      【讨论】:

        【解决方案3】:

        Class::DBI会为你做查询和转换。不过,我相信DBIx::Class 现在更受欢迎。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-26
          • 2015-07-20
          • 2013-12-03
          • 2014-09-28
          • 1970-01-01
          • 2014-11-09
          • 2016-02-25
          • 1970-01-01
          相关资源
          最近更新 更多