简体   繁体   中英

Perl and DBI - Load array Problem

I am 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 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM