如何使用DBI从数据库获取单个计数值? [英] How can I fetch a single count value from a database with DBI?

查看:124
本文介绍了如何使用DBI从数据库获取单个计数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码似乎太多了,得到一个单一的计数值。
有没有更好的,建议的方法使用纯DBI获取单个COUNT值?

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?

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];
}


推荐答案

没有额外的变量:

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

这篇关于如何使用DBI从数据库获取单个计数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆