First, 'no data found' is not an exception, it just means
there was no data found. Happens all the time
:-) If you want your code to treat that as
an exception, that's another matter handled inside
your script.
For dealing with exceptions, a very common idiom
is something like the following code. This uses the
RaiseError attribute of the database handle
to throw a die whenever we encounter a database
error. (And as we've said, finding no matching rows
isn't a database error.)
#!/usr/bin/perl
use strict;
use DBI;
my $last_name = 'user';
my $dbh = DBI->connect( 'DBI:mysql:mydb', 'cwinters', '',
{ RaiseError => 1, PrintError => 0 } )
|| die "Cannot connect to database! Error: $DBI::errstr";
my $sql = qq/SELECT first_name, last_name, login_name
FROM sys_user
WHERE last_name = ?/;
my ( $sth );
eval {
$sth = $dbh->prepare( $sql );
$sth->execute( $last_name );
};
if ( $@ ) {
print "Could not execute database statement! (Error: $@)";
$dbh->disconnect;
exit;
}
print "Users with last name: $last_name\n", "=" x 40, "\n";
while ( my $row = $sth->fetchrow_arrayref ) {
print "$row->[0] $row->[1] ($row->[2])\n";
}
$dbh->disconnect;
This gives the output:
Users with last name: user
========================================
Super User (superuser)
Joe User (joe)
test user (tester1)
However, if I change the SQL statement to:
my $sql = qq/SELECT first_name, last_name, login_name
FROM sys_user_bad_table_name
WHERE last_name = ?/;
I get something like:
Could not execute database statement! (Error: DBD::mysql::st
execute failed: Table 'mydb.sys_user_bad_table_name' doesn't
exist at pm_dbi_exception.pl line 16.)
The exact statement will, of course, depend on your
database and driver. As I understand, Oracle has a vast set
of codes used to indicate error conditions. If $@
exists after an eval block, you can inspect it
with a regex to pull out that code and act
appropriately.
Chris
M-x auto-bs-mode |