如何检查Perl中的DBI查询是否返回了多条记录?

时间:2009-04-29 11:33:04

标签: perl hash count dbi

我已经在网站上搜索了这个,但找不到任何回答我问题的内容。这让我了解详情:

我使用简单的选择查询来查询数据库,实际上(给定方案)它应该永远不会返回超过大约5到6条记录。我只是想检查是否已经退回了多个。如果只有一个已经返回,那么如果只有一个已经返回,那么我将继续使用该脚本。


my $sql = qq { SELECT col1, col2, col3
                 FROM table
            WHERE col1 = 'foo'
          };

my $sth = $dbc->prepare_cached($sql) or die "Could not prepare statement: " . $dbc->errstr;

$sth->execute() or die "Could not execute statement: " . $sth->errstr;

# Not sure how to efficiently check for more than one row returned and still progress if true... This is my problem! I'm thinking a nested if to see if any rows were returned, and then progress with the check of one or more rows? But how can this me checked (like a count function?)
if (my $ref = $sth->fetchrow_hashref()) {

 # One row was returned...

} else {
 # More than one row was returned... Uh oh!
}

如果你们知道一个我无法找到答案的帖子这个问题,只需重定向我,我就会使这个帖子无效!

此致 BorisTheBulletDodger!

4 个答案:

答案 0 :(得分:6)

my $sth = $dbh->prepare("SELECT col1, col2, col3 FROM tablename");
$sth->execute();
my $rows = $sth->fetchall_arrayref({});
if (@$rows == 0) {
    die "no rows returned";
} elsif (@$rows > 1) {
    die "too many rows returned";
}
my $row = $rows->[0];
print "col1 is $row->{col1}\n";

答案 1 :(得分:5)

my $sth = $dbh->prepare();
$sth->execute();

my $row = $sth->fetchrow_hashref();
my $second = $sth->fetchrow_hashref();

if ($second) {
  print "2+ rows\n";
} elsif ($row) {
  print "1 row\n";
} else {
  print "no rows\n";
}

答案 2 :(得分:4)

权威性地确定SELECT是否找到多行的唯一方法是尝试检索多行。 DBI确实提供了->rows属性,但它只能保证适用于非SELECT语句。

How can I check if a database query will return results?的答案也可能有用,即使问题不完全相同。

答案 3 :(得分:1)

使用fetchall_*selectall_*方法之一(请参阅DBI documentation),因为您最多只有5-6个。然后确定你毕竟有多少行。