How do I know how many rows a Perl DBI query returns?

后端 未结 7 869
遥遥无期
遥遥无期 2020-12-15 18:51

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

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 19:07

    In general, I'm not sure why people are so afraid of exceptions. You catch them and move on.

    my $sth = prepare ...
    $sth->execute;
    my $result = eval { $sth->fetchrow_arrayref->[1] };
    
    if($result){ say "OH HAI. YOU HAVE A RESULT." }
    else       { say "0 row(s) returned."         }
    

    In this case, though, Paul's answer is best.

    Also, $sth->rows doesn't usually work until you have fetched every row. If you want to know how many rows match, then you have to actually ask the database engine the question you want to know the answer to; namely select count(1) from foo where bar='baz'.

提交回复
热议问题