Dbi Error Handling
Contents |
the answer generally runs along the lines of "Why aren't you performing error checking?" Sure enough, nine out of
Dbi Raiseerror
ten times when error checking is added, the exact error message perl dbi escape appears and the cause for error is obvious. 4.5.1. Automatic Versus Manual Error Checking Early versions of perl dbi execute error handling 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 that returned
Perl Dbi Connect Error Handling
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 error-handling capability in
Perl Dbi Error String
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 form of error checking is more
login Username: * Password: * Create new accountRequest new password Home » DBI: handling database errors ( categories: databases ) Basically, there are two ways perl dbi catch error of handling database errors, check (almost) every DBI call for errors or set 'RaiseError'
Dbi Error Fatal
attribute to '1ยด: -- Manual checking This way, you have to add code yourself to check for database error conditions, so perl dbi autocommit after nearly every method call you should check if the operation completed successfully. There are two DBI methods that are very helpful to manually check for database errors: 'err' and 'errstr'. 'err' returns the native http://docstore.mik.ua/orelly/linux/dbi/ch04_05.htm database engine error code from the last DBI method called. The code returned is usually an integer. 'errstr' returns the native database engine error message from the last DBI method called. Example: $dbh = DBI->connect($data_src, $user, $pwd) or die $DBI::errstr;
my $sth = $dbh->prepare("DELETE FROM table WHERE count < '?'");
$sth->execute(25);
if ( $sth->err )
{
die "ERROR! return code: . $sth->err http://www.perlhowto.com/dbi_handling_database_errors . " error msg: " . $sth->errstr . "\n";
}
-- Setting 'RaiseError' attribute If DBI 'RaiseError' attribute is set to '1' (is '0' by default), then any database error will cause the DBI module to 'die' with an appropriate message. When using 'RaiseError', is recommended to set the 'PrintError' atribute to '0') Example: my $dbh = DBI->connect($dsn, $user, $pw, { RaiseError => 1, PrintError => 0 });
Bookmark/Search this post with: | | | | » login or register to post comments You can also provide a Submitted by Kelicula on Wed, 04/15/2009 - 00:58. You can also provide a custom sub to handle errors with the RaiseError flag set. After establishing server connection: $dbh->{HandleError} = sub { my $error = shift; # do something with error...; }; Or in attributes: my $dbh = DBI->connect("DBI:......, { RaiseError => 1, HandleError => \&DBerror })|| die $DBI::errstr; sub DBerror { my $error = shift; # do something with error... } etc... Only disadvantage is knowing what line the error originated from in your script. -------- I'm unique just like everyone else! » login or register to post comments Home | Links | RSS feed | Forums Copyright © 2006 Toshiro Viera Stalker - All right
Related Modules Rose::DB::Object DBIx::Class Class::DBI more... By perlmonks.org CPAN RT New 14 http://search.cpan.org/perldoc/DBI Open 11 Stalled 4 View/Report Bugs Module Version: 1.636 Source NAME SYNOPSIS GETTING HELP General Mailing Lists IRC Online Reporting http://rio.murmansk.ru/doc_/dbi/ch06_01.htm a Bug NOTES DESCRIPTION Architecture of a DBI Application Notation and Conventions Outline Usage General Interface Rules & Caveats Naming Conventions and perl dbi Name Space SQL - A Query Language Placeholders and Bind Values THE DBI PACKAGE AND CLASS DBI Constants DBI Class Methods parse_dsn connect connect_cached available_drivers installed_drivers installed_versions data_sources trace visit_handles DBI Utility Functions data_string_desc data_string_diff data_diff neat neat_list looks_like_number hash sql_type_cast DBI Dynamic Attributes $DBI::err dbi error handling $DBI::errstr $DBI::state $DBI::rows $DBI::lasth METHODS COMMON TO ALL HANDLES err errstr state set_err trace trace_msg func can parse_trace_flags parse_trace_flag private_attribute_info swap_inner_handle visit_child_handles ATTRIBUTES COMMON TO ALL HANDLES Warn Active Executed Kids ActiveKids CachedKids Type ChildHandles CompatMode InactiveDestroy AutoInactiveDestroy PrintWarn PrintError RaiseError HandleError HandleSetErr ErrCount ShowErrorStatement TraceLevel FetchHashKeyName ChopBlanks LongReadLen LongTruncOk TaintIn TaintOut Taint Profile ReadOnly Callbacks private_your_module_name_* DBI DATABASE HANDLE OBJECTS Database Handle Methods clone data_sources do last_insert_id selectrow_array selectrow_arrayref selectrow_hashref selectall_arrayref selectall_array selectall_hashref selectcol_arrayref prepare prepare_cached commit rollback begin_work disconnect ping get_info table_info column_info primary_key_info primary_key foreign_key_info statistics_info tables type_info_all type_info quote quote_identifier take_imp_data Database Handle Attributes AutoCommit Driver Name Statement RowCacheSize Username DBI STATEMENT HANDLE OBJECTS Statement Handle Methods bind_param bind_param_inout bind_param_array execute execute_array execute_for_fetch fetchrow_arrayref fetchrow_array fetchrow_hashref fetchall_arrayref fetchall_hashref finish rows bind_col bind_columns dump_results Statement Handle Attributes NUM_O
to alter the way in which the database and statement handles function on-the-fly, as well as how to use explicit transaction handling within your database. These topics are not strictly necessary for basic DBI usage, but they contain useful information that will allows you to maximize the potential of your DBI programs. 6.1. Handle Attributes and Metadata In addition to methods associated with database and statement handles, the DBI also defines attributes for these handles that allow the developer to examine or fine-tune the environment in which the handles operate. Some attributes are unique to either database or statement handles, and some are common to both. The attribute values of a handle can be thought of as a hash of key/value pairs, and can be manipulated in the same way as you would manipulate an ordinary hash via a reference. Here are a few examples using the AutoCommit attribute: ### Set the database handle attribute "AutoCommit" to 1 (e.g., on) $dbh->{AutoCommit} = 1; ### Fetch the current value of "AutoCommit" from the handle $foo = $dbh->{AutoCommit}; Fetching attributes as hash values, rather than as method calls, has the added bonus that the hash lookup can be interpolated inside double-quoted strings: ### Print the current value of "AutoCommit" from the handle print "AutoCommit: $dbh->{AutoCommit}\n"; With AutoCommit enabled, that would print: AutoCommit: 1 as you might expect. Actually, since AutoCommit is a boolean attribute, it would print 1 after any value that Perl considers true had been assigned to it. After a false value was assigned, you may reasonably expect a 0 to be printed, but you might be surprised to see: AutoCommit: That's because Perl uses an internal representation of false that is both a numeric zero and an empty string at the same time. When used in a string context, the empty string is printed. In a numeric context, the zero is used. When getting or setting an attribute value, the DBI automatically checks that the attribute name you are using and generates an error if it's not known.[55] Similarly, any attempts to set a read-only attribute will result in an error. Be aware, however, that these errors are reported using die() regardless of the setting of the RaiseError attribute, and are thus potentially fatal. That's another good reason to use eval {...} blocks, as we discussed in Chapter 4, "Programming with the DBI ". [55]Dri