Perl Dbi Connect Error Handling
Contents |
the answer generally runs along the lines of "Why aren't you performing error checking?" Sure enough, nine out of ten perl dbi error handling examples times when error checking is added, the exact error message appears and perl dbi handleerror the cause for error is obvious. 4.5.1. Automatic Versus Manual Error Checking Early versions of the DBI required perl dbi execute return value programmers to perform their own error checking, in a traditional way similar to the examples listed earlier for connecting to a database. Each method that returned some sort of perl dbi errstr 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 error-handling capability in the style of exception
Perl Dbi Try Catch
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 form of error checking is more akin to classic C and Perl programming, where each impor
Go to comments The DBI module lets you handle errors yourself if you don't like its built-in behavior. DBI
Dbi Error Fatal
lets you handle the errors at either the database or the try catch in perl statement handle level by specifying attributes: my $dbh = DBI->connect( ..., ..., \%attr ); my $sth = $dbh->prepare( dbi err fatal ..., \%attr ); There are several attributes that affect error handling, each of which you can use with either a connection or a statement handle: Attribute Type Default PrintWarn http://docstore.mik.ua/orelly/linux/dbi/ch04_05.htm Boolean On PrintError Boolean On RaiseError Boolean Off HandleError Code Ref Off ShowErrorStatement Boolean Off These attributes are inherited by anything derived from the handle where you set them. The PrintWarn and PrintError attributes do just what they say. They are on by default, and they don't stop your program. In this example, you prepare a statement that expects https://www.effectiveperlprogramming.com/2010/07/set-custom-dbi-error-handlers/ one bind parameter, but when you execute it, you give two parameters instead: use DBI; my $dbh = DBI->connect( 'dbi:SQLite:dbname=test.db', '', '', {} ); my $sth = $dbh->prepare( 'SELECT * FROM Cats WHERE id = ?' ); $sth->execute( 1, 2 ); while( my @row = $sth->fetchrow_array ) { print "row: @row\n"; } print "Got to the end\n"; Since PrintError is true by default, DBI prints the error, but it allows the program to continue even though there was an error: DBD::SQLite::st execute failed: called with 2 bind variables when 1 are needed at dbi-test.pl line 12. Got to the end If you set the ShowErrorStatement attribute, you get a better error message because DBI appends the SQL statement that you tried to execute. You can set this either database handle or the statement handle, but if you don't know which statement is causing the problem, it's easier to set it as part of the database handle: # The rest of the program is the same my $dbh = DBI->connect( 'dbi:SQLite:dbname=test.db', '', '', { ShowError
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 http://zetcode.com/db/mysqlperl/err/ $DBI::errEquivalent to $h->err() $DBI::errstrEquivalent to $h->errstr() $DBI::stateEquivalent to $h->state() The second table gives a list of DBI dynamic attributes, which are related to error handling. These attributes have a short lifespan. They should be used immediately after the method that might cause an error. Default error handling By default, the errors are returned by Perl DBI methods. #!/usr/bin/perl use strict; use DBI; my $dsn = "dbi:mysql:dbname=mydb"; my $user = perl dbi "user12"; my $password = "34klq*"; my $dbh = DBI->connect($dsn, $user, $password) 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 perl dbi connect warn $DBI::errstr if $DBI::err; $sth->finish(); $dbh->disconnect(); In the first script we deal with the default 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 had a larger script. The preferred way of dealing with possible errors is to raise exceptions. To raise exceptions, we set the RaiseError attribute to tr