如何使用 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;
}
虽然这个比较短,但我还是有两句话。
sub get_count_2 {
my $ar = $dbh->selectall_arrayref("SELECT ...", undef, @params)
return $ar->[0][0];
}
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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
很容易在一行中完成,无需额外变量:
Easy enough to do in one line with no extra variables:
我不了解 Perl,但如果它的语法符合逻辑,我认为这可以根据您的第二个示例进行:
I don't know Perl, but if it's syntax is logical I would think this would work based on your 2nd example:
我自己可能不会这样做,但您始终可以将其作为您正在使用的 DBH 对象的新顶级函数:
警告:下面是未经测试的代码!
然后这样调用它:
除了污染不属于您的命名空间之外,您还必须为您使用的每个数据库驱动程序编写此内容,尽管我确信您可以做一些事情来允许您构造和评估一些代码为给定的 DBH 对象自动配置它。
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:
WARNING: untested code follows!
and then call it like this:
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.