开发者

Perl and DBI - Load array Problem

I am开发者_StackOverflow社区 new to Perl and need some help.

In Mysql I have a table with a todo-List filled up.

At the beginning of my script, I want to add these values to "my %todo"

But I can't figure out how to do this...

Any idea?


OK, let's play martian rover though I'd rather see the code.

Do you use warnings; use strict? If not, do it. If yes, are there any warnings or errors?

If you put a print "while\n"; into your while loop, how many while's will you get on screen? How many records are there in the table?

If you use DBI, turn on exceptions: $dbh->RaiseError(1); ($dbh is you database handle here) before any operations with DB.


I don't understand why you ask for "load array" and specify a hash %todo, but if you want to read a table into memory once, you should look at the $dbh->selectall_arrayref() method.

Added: See if this get you started:

    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();


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜