在 Perl 中使用 selectrow_array 获取 2 个值

Fetch 2 values using selectrow_array in Perl

我最近发现有一个 selectrow_array 函数可以从数据库中获取值。我在使用它时遇到以下错误。我想知道这里的问题是什么,找不到替代方法。

代码是:

my $db_connection = DBI->connect($dsn, $dbuser, $dbpassword ) or die $DBI::errstr;

my $sql_statement = "SELECT customer_id,quota FROM customer_call_quota WHERE quota>=1";

while (my $row = $db_connection->selectrow_array($sql_statement)) {
     my ($cust_id, $quota) = @$row; #<---- error line
 }

my $rc = $db_connection->disconnect ;
return "ok";

错误:

Can't use string ("value") as an ARRAY ref while "strict refs" in use at code.pl line ...

两个问题。

  • selectrow_array 不是 return 对数组的引用。那是 selectrow_arrayref.
  • selectrow_* 第一行只有 return。

解决方案:

# Wasteful

my $sth = $dbh->prepare($sql_statement);
$sth->execute();
while (my @row = $sth->fetchrow_array()) {
    my ($cust_id, $quota) = @row;
    ...
}

my $sth = $dbh->prepare($sql_statement);
$sth->execute();
while (my ($cust_id, $quota) = $sth->fetchrow_array()) {
    ...
}

my $sth = $dbh->prepare($sql_statement);
$sth->execute();
while (my $row = $sth->fetch()) {
    my ($cust_id, $quota) = @$row;
    ...
}