【发布时间】:2011-07-23 20:08:57
【问题描述】:
我是 Perl 新手,需要一些帮助。
在 Mysql 中,我有一个填满待办事项列表的表。
在脚本的开头,我想将这些值添加到 "my %todo"
但我不知道该怎么做……
有什么想法吗?
【问题讨论】:
我是 Perl 新手,需要一些帮助。
在 Mysql 中,我有一个填满待办事项列表的表。
在脚本的开头,我想将这些值添加到 "my %todo"
但我不知道该怎么做……
有什么想法吗?
【问题讨论】:
好吧,让我们玩火星车吧,虽然我更愿意看代码。
你use warnings; use strict吗?如果没有,那就去做吧。如果是,是否有任何警告或错误?
如果您将print "while\n"; 放入您的while 循环中,您将在屏幕上显示多少while?表中有多少条记录?
如果您使用 DBI,请在对 DB 进行任何操作之前打开异常:$dbh->RaiseError(1);($dbh 是您这里的数据库句柄)。
【讨论】:
我不明白你为什么要求“加载数组”并指定一个哈希 %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();
【讨论】:
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;
【讨论】: