Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a setup where I am accessing Oracle 8i data from CGI scripts, to do a select which does not fail, i first do a select count(*) with a where condition and only if the count returned is greater than zero, I execute the select statement withe the same where condition. It works but I know that this is not the most efficient way of doing it. Any suggestions. Could someone tell me more about how to handle DB exceptions (No data found, too many rows fetched, zero divide etc)

Replies are listed 'Best First'.
Re: How to handle No Data Found ...
by lachoy (Parson) on May 01, 2001 at 15:49 UTC

    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

Re: How to handle No Data Found ...
by Anonymous Monk on May 01, 2001 at 12:55 UTC
    some posted code would help too