我怎么知道Perl DBI查询返回多少行? [英] How do I know how many rows a Perl DBI query returns?
问题描述
我基本上试图使用Perl在数据库中进行搜索,以判断是否存在具有特定ID的项目.此搜索不能返回任何行,但是也可以返回一个行.
I'm trying to basically do a search through the database with Perl to tell if there is an item with a certain ID. This search can return no rows, but it can also return one.
我有以下代码:
my $th = $dbh->prepare(qq{SELECT bi_exim_id FROM bounce_info WHERE bi_exim_id = '$exid'});
$th->execute();
if ($th->fetch()->[0] != $exid) {
...
基本上,这将尝试查看是否返回了ID,如果没有返回,请继续执行脚本.但是它在$th->fetch()->[0]
上引发了Null数组引用错误.
我怎样才能简单地检查它是否返回行还是现在?
Basically, this tries to see if the ID was returned and if it's not, continue with the script. But it is throwing a Null array reference error on the $th->fetch()->[0]
thing.
How can i just simply check to see if it returned rows or now?
推荐答案
my $th = $dbh->prepare(qq{SELECT bi_exim_id FROM bounce_info WHERE bi_exim_id = '$exid'});
$th->execute();
my $found = 0;
while ($th->fetch())
{
$found = 1;
}
如果该行不存在,您的查询将不会返回任何内容,因此您无法取消对提取的引用.
Your query won't return anything if the row doesn't exist, so you can't de-reference the fetch.
更新:您可能希望将其重写为
Update: you might want to re-write that as
my $found = $th->fetch();
这篇关于我怎么知道Perl DBI查询返回多少行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!