17

对于获取单个计数值,以下代码似乎太多了。有没有更好的推荐方法来使用普通 DBI 获取单个 COUNT 值?

sub get_count {
   my $sth = $dbh->prepare("SELECT COUNT(*) FROM table WHERE...");
   $sth->execute( @params );
   my $($count) = $sth->fetchrow_array;
   $sth->finish;

   return $count;
}

这更短,但我仍然有两个陈述。

sub get_count_2 {
   my $ar = $dbh->selectall_arrayref("SELECT ...", undef, @params)
   return $ar->[0][0];
}
4

3 回答 3

35

很容易在一行中完成,没有额外的变量:

$count = $dbh->selectrow_array('SELECT count(*) FROM table WHERE...', undef, @params);
于 2009-11-01T12:32:44.717 回答
3

我不知道 Perl,但如果它的语法是合乎逻辑的,我认为这将基于您的第二个示例:

sub get_count {
   return $dbh->selectall_arrayref("SELECT ...", undef, @params)->[0][0];
}
于 2009-11-01T11:24:58.360 回答
1

我自己可能不会这样做,但您始终可以将其作为您正在使用的 DBH 对象的新顶级函数:

警告:未经测试的代码如下!

sub DBD::SQLite::db::count
{
   my($dbh, $table, $where) = @_;

   my($stmt) = "SELECT COUNT(*) FROM $table";
   $stmt .= " WHERE $where" if $where;

   my($count) = $dbh->selectrow_array($stmt);

   return $count;

}

然后这样称呼它:

my($cnt) = $dbh->count('Employee', 'year_hired < 2000');

Besides polluting a namespace that's not yours, you'd also have to write this for every DB driver you use, though I'm sure your could work something up that allows you to construct and eval some code to auto-configure this for a given DBH object.

于 2009-11-01T14:13:51.813 回答