database 如何使用 DBI 从数据库中获取单个计数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1656748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 07:30:43  来源:igfitidea点击:

How can I fetch a single count value from a database with DBI?

databaseperldbi

提问by szabgab

The following code seems to be just too much, for getting a single count value. Is there a better, recommended way to fetch a single COUNT value using plain DBI?

以下代码似乎太多了,无法获得单个计数值。是否有更好的推荐方法来使用普通 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;
}

This is shorter, but I still have two statements.

这是较短的,但我仍然有两个声明。

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

回答by Dave Sherohman

Easy enough to do in one line with no extra variables:

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

$count = $dbh->selectrow_array('SELECT count(*) FROM table WHERE...', undef, @params);

回答by Tony Andrews

I don't know Perl, but if it's syntax is logical I would think this would work based on your 2nd example:

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

sub get_count {
   return $dbh->selectall_arrayref("SELECT ...", undef, @params)->[0][0];
}

回答by Joe Casadonte

I probably wouldn't do this myself, but you could always make it a new top-level function of the DBH object you're using:

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

WARNING: untested code follows!

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

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;

}

and then call it like this:

然后像这样调用它:

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.

除了污染不属于你的命名空间之外,你还必须为你使用的每个数据库驱动程序编写这个,尽管我相信你可以做一些事情,让你构造和评估一些代码来为给定的自动配置它DBH 对象。