Database Error Handling In Perl
Contents |
the answer generally runs along the lines of "Why aren't you performing error checking?" Sure enough, nine out perl error handling eval of ten times when error checking is added, the exact error perl error handling best practices message appears and the cause for error is obvious. 4.5.1. Automatic Versus Manual Error Checking Early versions perl dbi error handling of the DBI required programmers to perform their own error checking, in a traditional way similar to the examples listed earlier for connecting to a database. Each method
Exception Handling In Perl
that returned some sort of status indicator as to its success or failure should have been followed by an error condition checking statement. This is an excellent, slightly C-esque way of programming, but it quickly gets to be tiresome, and the temptation to skip the error checking grows. The DBI now has a far more straightforward exception handling in perl example error-handling capability in the style of exception s. That is, when DBI internally detects that an error has occurred after a DBI method call, it can automatically either warn() or die() with an appropriate message. This shifts the onus of error checking away from the programmer and onto DBI itself, which does the job in the reliable and tireless way that you'd expect. Manual error checking still has a place in some applications where failures are expected and common. For example, should a database connection attempt fail, your program can detect the error, sleep for five minutes, and automatically re-attempt a connection. With automatic error checking, your program will exit, telling you only that the connection attempt failed. DBI allows mixing and matching of error-checking styles by allowing you to selectively enable and disable automatic error checking on a per-handle basis. 4.5.1.1. Manual error checking Of course, the DBI still allows you to manually error check your programs and the execution of DBI methods. This fo
native database engine error message from the last DBI method called. $h->state()Returns a state code in the standard SQLSTATE five character format The above three methods deal with error messages. DBI dynamic attributeDescription $DBI::errEquivalent to $h->err() $DBI::errstrEquivalent to $h->errstr() perl catch error $DBI::stateEquivalent to $h->state() The second table gives a list of DBI dynamic attributes, which are
Perl Dbi Escape
related to error handling. These attributes have a short lifespan. They should be used immediately after the method that might cause an
Perl Exception Class
error. Default error handling By default, the errors are returned by Perl DBI methods. #!/usr/bin/perl use strict; use DBI; my $dsn = "dbi:SQLite:dbname=test.db"; my $user = ''; my $password = ''; my $dbh = DBI->connect($dsn, $user, $password) http://docstore.mik.ua/orelly/linux/dbi/ch04_05.htm or die "Can't connect to database: $DBI::errstr"; my $sth = $dbh->prepare( q{ SELECT Id, Name, Price FROM Cars } ) or die "Can't prepare statement: $DBI::errstr"; my $rc = $sth->execute() or die "Can't execute statement: $DBI::errstr"; while (my($id, $name, $price) = $sth->fetchrow()) { print "$id $name $price\n"; } # check for problems which may have terminated the fetch early warn $DBI::errstr if $DBI::err; $sth->finish(); $dbh->disconnect(); In the first script we deal with the default http://zetcode.com/db/sqliteperltutorial/err/ behaviour of returning error codes. my $dbh = DBI->connect($dsn, $user, $password) or die "Can't connect to database: $DBI::errstr"; We call the connect() method to create a database connection. If the attempt fails, the method returns undef and sets both $DBI::err and $DBI::errstr attributes. The die() method prints the error message in case of a failure and terminates the script. my $sth = $dbh->prepare( q{ SELECT Id, Name, Price FROM Cars } ) or die "Can't prepare statement: $DBI::errstr"; We call the prepare() statement. If the method fails, the die() method prints an error message and terminates the script. my $rc = $sth->execute() or die "Can't execute statement: $DBI::errstr"; Again. We call the execute() method and check for errors. The method returns undef if it fails. warn $DBI::errstr if $DBI::err; We check for problems which may have terminated the fetch method early. Raising exceptions Checking for errors each time we call a DBI method may be tedious. We could easily forget to do so if we have a larger script. The preferred way of dealing with possible errors is to raise exceptions. To raise exceptions, we set the RaiseError attribute to true. #!/usr/bin/perl use strict; use DBI; my $dsn = "dbi:SQLite:dbname=test.db"; my $user = ''; my $password = ''; my %attr = ( RaiseError => 1 ); my $dbh = DBI->co
Tutorials Poetry RecentThreads NewestNodes Donate What'sNew on Apr 14, 2000 at 03:36UTC ( #7568=perltutorial: print w/replies, xml ) Need Help?? Tricks with DBI 1. Check for database errors. You're going to run into errors with databases for similar reasons that you do when using system http://www.perlmonks.org/?node_id=7568 calls and the like. And just as you should always check the return code of your system calls, so should you always check the return status of your database calls. The easiest way to do this is by setting DBI's RaiseError attribute to 1; first connect to the database (and check the return), then set the RaiseError attribute: my $dbh = DBI->connect('foo', 'bar', 'baz', 'mysql') or die "Can't connect: ", $DBI::errstr; error handling $dbh->{RaiseError} = 1; [download] By doing this, you ensure that any database error will cause a die. Why is this good? Because generally, if you're writing a database application and you have a database error, you don't want to continue as if nothing happened. :) (Besides, you can always catch the die in an eval; just make sure that you handle the errors rather than ignoring them.) The other way to check handling in perl for errors, of course, is to check the return of each method call, eg.: my $sth = $dbh->prepare("select id from foo") or die "Can't prepare: ", $dbh->errstr; $sth->execute or die "Can't execute: ", $dbh->errstr; [download] So as not to make your code one big C-like mess of error checking, though, you might as well just use RaiseError. 2. Use placeholders instead of literal values. This is covered pretty thoroughly in What are placeholders in DBI. Suffice it to say here, then, that you should use placeholders instead of literal values. Always (or pretty much, at least). And, for the same reasons, you should use prepare_cached instead of prepare. 3. The fastest way to fetch. When you execute a SELECT statement, you want to get the data back as quickly as possible. The fastest way to do this is to use the bind_columns and fetch methods, because they don't copy a bunch of memory around. bind_columns binds Perl variables to columns returned from your SELECT statement. For example, if you had the following SQL statement: select id, name, phone from people [download] You'd want to bind 3 variables to the associated columns. So you set up the variables, then use bind_columns to bind them: my($id, $name, $phone); $sth->bind_columns(undef, \$id, \$name, \$phone); [download] (The first argu