Perl $dbh - Do Error
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
Perl Dbi Execute Return Value
and the cause for error is obvious. 4.5.1. Automatic Versus Manual Error Checking Early versions of the DBI perl dbi handleerror 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 some sort perl dbi connect error handling 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 the style of
Perl Dbi Errstr
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 akin to classic C and Perl prog
Related Modules Rose::DB::Object DBIx::Class Class::DBI more... By perlmonks.org CPAN RT New 14 Open 11 Stalled perl dbi try catch 4 View/Report Bugs Module Version: 1.636 Source NAME dbi error fatal SYNOPSIS GETTING HELP General Mailing Lists IRC Online Reporting a Bug NOTES DESCRIPTION Architecture
Try Catch In Perl
of a DBI Application Notation and Conventions Outline Usage General Interface Rules & Caveats Naming Conventions and Name Space SQL - A Query Language http://docstore.mik.ua/orelly/linux/dbi/ch04_05.htm 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::errstr $DBI::state $DBI::rows $DBI::lasth METHODS COMMON TO ALL HANDLES http://search.cpan.org/perldoc?DBI 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_OF_FIELDS NUM_OF_PARAMS NAME NAME_lc NAME_uc NAME_hash NAME_lc_hash NAME_uc_hash TYPE PRECISION SCALE NULLABLE CursorName Database Statement ParamValues ParamTypes ParamArrays RowsInCache FURTHE
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 calls and the like. And just as http://www.perlmonks.org/?node_id=7568 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; $dbh->{RaiseError} = 1; [download] By doing this, you ensure that perl dbi 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 for errors, of course, is to check the return of each method call, perl $dbh - 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 argument to bind_columns is actually a hash reference specifying DBI attributes to associate with this particular method; we don't want