在Perl中使用selectrow_array获取2个值

时间:2017-03-13 05:00:27

标签: mysql arrays perl fetch

我最近发现有一个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 ...

1 个答案:

答案 0 :(得分:2)

两个问题。

  • selectrow_array不会返回对数组的引用。那是selectrow_arrayref
  • selectrow_*只返回第一行。

解决方案:

# 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;
    ...
}