Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 452
The.Anti.9 Avatar asked Jan 13 '09 21:01

The.Anti.9


People also ask

What is DBI in Perl?

The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used.

What is the correct sequence of database operation in Perl?

First, you connect to the MySQL database using the DBI->connect() method. Second, you use prepare() method of the database handler object, that accepts an SQL statement as an argument.


1 Answers

The DBD::mysql driver has a the rows() method that can return the count of the results:

$sth = $dbh->prepare( ... );
$sth->execute;
$rows = $sth->rows;

This is database-driver specific, so it might not work in other drivers, or it might work differently in other drivers.

like image 106
brian d foy Avatar answered Sep 30 '22 01:09

brian d foy