【问题标题】:Perl and DBI - Load array ProblemPerl 和 DBI - 加载数组问题
【发布时间】:2011-07-23 20:08:57
【问题描述】:

我是 Perl 新手,需要一些帮助。

在 Mysql 中,我有一个填满待办事项列表的表。

在脚本的开头,我想将这些值添加到 "my %todo"

但我不知道该怎么做……

有什么想法吗?

【问题讨论】:

    标签: mysql arrays perl dbi


    【解决方案1】:

    好吧,让我们玩火星车吧,虽然我更愿意看代码。

    use warnings; use strict吗?如果没有,那就去做吧。如果是,是否有任何警告或错误?

    如果您将print "while\n"; 放入您的while 循环中,您将在屏幕上显示多少while?表中有多少条记录?

    如果您使用 DBI,请在对 DB 进行任何操作之前打开异常:$dbh->RaiseError(1);($dbh 是您这里的数据库句柄)。

    【讨论】:

      【解决方案2】:

      我不明白你为什么要求“加载数组”并指定一个哈希 %todo,但是如果你想将一个表读入内存一次,你应该看看 $dbh->selectall_arrayref() 方法。

      添加:看看这是否能让你开始:

          my $dsn = '...';
          my $user = '...';
          my $password = '...';
          my $dbh = DBI->connect( $dsn, $user, $password, { RaiseError => 1, AutoCommit => 0 } );
          my $sql = 'SELECT ... FROM Todo';
          my %todo = ();
        if (0) {
          my $sth = $dbh->prepare( $sql );
          $sth->execute();
          while (my $aref = $sth->fetchrow_arrayref()) {
            $todo{ $aref->[ 0 ] } = $aref->[ 1 ];
          }
          $sth->finish();
        } else {
          my $aref = $dbh->selectall_arrayref($sql);
          for (@$aref) {
            $todo{ $_->[ 0 ] } = $_->[ 1 ];
          }
        }
          for (keys( %todo )) {
            print $_, "\n", $todo{ $_ }, "\n\n";
          }
          my $rc = $dbh->disconnect();
      

      【讨论】:

      • 对不起,如果我解释不好.. 我想加载 todo-tabe 的内容以保留在 %todo 中。我尝试使用 while 语句,但在结束 } 之后 %todo 未定义。知道我做错了什么吗?
      • @perlbeginner - 也许描述表和哈希结构和/或显示一些代码会有所帮助。
      • 该表只有一个唯一的 id (id) 和一个 todo 列。哈希应该具有相同的结构
      • “知道我做错了什么吗?”没有看到一些代码,真的很难说。
      【解决方案3】:
      use strict;
      use warnings;
      my $dbh = $dbh->connect;
      $dbh->{RaiseError} = 1;
      my $sth = $dbh->prepare(q/select id, to_do from to_do_table/);
      $sth->execute;
      my %todo;
      while(my ($id, $to_do) = $sth->fetchrow) {
          $todo{$index_column} = $to_do;
      }
      $dbh->disconnect;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-19
        • 2011-10-24
        • 1970-01-01
        • 1970-01-01
        • 2012-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多