Alex Rivera | Logout

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

Asked 2009-01-13T21:08:53.940
20

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.

I have the following code:

my $th = $dbh->prepare(qq{SELECT bi_exim_id FROM bounce_info WHERE bi_exim_id = '$exid'});
$th->execute();
if ($th->fetch()->[0] != $exid) {
        ...

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?

Edit
Report

1 Answer

4

Change select to always return something? This should work in Sybase, dunno about other DBs.

my $th = $dbh->prepare(qq{SELECT count(*) FROM bounce_info WHERE bi_exim_id = '$exid'});
$th->execute();
if ($th->fetch()->[0]) {
....
}
answered 2009-01-13T21:24:26.203

Your Answer