我是Perl的新手,需要一些帮助。
在Mysql中,我有一个填充了待办事项列表的表。
在我的脚本开头,我想将这些值添加到“my%todo”
但我无法弄清楚如何做到这一点......
有什么想法吗?
答案 0 :(得分:2)
好吧,让我们玩火星车,虽然我宁愿看到代码。
你use warnings; use strict
?如果没有,那就去做吧。如果是,是否有任何警告或错误?
如果您将print "while\n";
放入while循环中,屏幕上会显示多少while
?表中有多少条记录?
如果您使用DBI,请在使用DB进行任何操作之前启用例外:$dbh->RaiseError(1);
(此处为$ dbh是数据库句柄)。
答案 1 :(得分:1)
我不明白你为什么要求“load array”并指定一个hash%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();
答案 2 :(得分:0)
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;