Dbi Perl Error Handling
Contents |
the answer generally runs along the lines of "Why aren't you performing error checking?" Sure enough, nine out of ten times when error checking is added, the exact error message appears and the cause for error perl dbi get error message is obvious. 4.5.1. Automatic Versus Manual Error Checking Early versions of the DBI required programmers perl dbi raiseerror to perform their own error checking, in a traditional way similar to the examples listed earlier for connecting to a database. Each
Perl Dbi Errstr
method 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
Perl Eval
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 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 perl dbi statement handle 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 important statement is checked to ensure that it has executed successfully, allowing the program to take evasive action upon failure. DBI, by default, performs basic automatic error reporting for you by enabling the PrintError attribute. To disable this feature, simply set the value to 0 either via the handle itself after instantiation, or, in the case of database handles, via the attribute hash of the connect( ) method. For example: ### Attributes to pass to DBI->connect( ) %attr = ( PrintError => 0, RaiseError => 0 ); ### Connect... my $dbh = DBI->connect( "dbi:Oracle
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the
Perl Dbi Statement Handle Still Active
company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions perl dbi connect error Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million perl dbi error string programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Perl DBI - Capturing errors up vote 7 down vote favorite 2 Whats the best way of capturing any DBI http://docstore.mik.ua/orelly/linux/dbi/ch04_05.htm errors in Perl. So for example if an insert fails because there were illegal characters in the values being inserted, how can I not have the script fail, but capture the error and handle it appropriately. I don't want to do the "or die" coz I don't want to stop execution of the script. perl exception error-handling dbi share|improve this question edited Jan 27 '11 at 23:10 Ether 39.8k1065140 asked Jan 27 '11 http://stackoverflow.com/questions/4822991/perl-dbi-capturing-errors at 23:02 Chris 64331422 add a comment| 2 Answers 2 active oldest votes up vote 12 down vote accepted Use the RaiseError=>1 configuration in DBI->connect, and wrap your calls to the $dbh and $sth in a try block (TryCatch and Try::Tiny are good implementations for try blocks). See the docs for more information on other connect variables available. for example: use strict; use warnings; use DBI; use Try::Tiny; my $dbh = DBI->connect( $your_dsn_here, $user, $password, { PrintError => 0, PrintWarn => 1, RaiseError => 1, AutoCommit => 1, } ); try { # deliberate typo in query here my $data = $dbh->selectall_arrayref('SOHW TABLES', {}); } catch { warn "got dbi error: $_"; }; share|improve this answer edited Jan 28 '11 at 3:16 cjm 52k794147 answered Jan 27 '11 at 23:03 Ether 39.8k1065140 1 Shouldn't you put the connect within the try block as well? –mscha Jan 27 '11 at 23:13 @mscha: that's not necessary - connect will return undef if it fails. (See the docs - you just need to check if a $dbh was returned.) –Ether Jan 27 '11 at 23:47 1 but you don't check. –mscha Jan 27 '11 at 23:48 3 @mscha: what do you think will happen when trying to call a method on an undefined reference ($dbh)? I
Related Modules Rose::DB::Object DBIx::Class Class::DBI more... By http://search.cpan.org/perldoc/DBI perlmonks.org CPAN RT New 14 Open 11 Stalled 4 View/Report Bugs Module Version: 1.636 Source NAME SYNOPSIS http://www.perlmonks.org/?node_id=268189 GETTING HELP General Mailing Lists IRC Online Reporting a Bug NOTES DESCRIPTION Architecture of a DBI Application Notation and perl dbi Conventions Outline Usage General Interface Rules & Caveats Naming Conventions and 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 perl dbi statement 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 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 H
PerlNews Q&A Tutorials Poetry RecentThreads NewestNodes Donate What'sNew on Jun 23, 2003 at 14:47UTC ( #268189=perlquestion: print w/replies, xml ) Need Help?? Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: Help ?!?!?Using DBI I call a PL/SQL package and hand it some variables. This package does some validation of the data, when the package is not happy with the data an SQL error is raised.What I want to do is instead of having DBI die, I want to see the error in a variable so I can process this and send back an error to the user.The variables are handed in via a webpage and errors should be returned on that page (thus the dislike of a die)I have seen some solutions to this, but these usualy use a eval{} to solve the problem. Due to the application framework that I'm forced to work in this will not work as a die is always caught before my code can get to it.So what I wat is a way to find the errors returned without death.The ways I have atempted to get these errors from the DBI are: - my $error = $dbh->errstr; - my $error = $@The problem is that both are always undefined no matter how may errors the package returns. So my question is how do I find the errors without having the DBI calling dieThis is my config: - Perl v5.6.1 built for sun4-solaris - DBI DBI version 1.34 - Oracle DBD complited with Oracle 8.1.7 clientComment on DBI - PL/SQL error catchingSelect or Download Code Replies are listed 'Best First'. Re: DBI - PL/SQL error catching by gmax (Abbot) on Jun 23, 2003 at 15:15UTC If eval id not a viable solution, then you have to check every DBI call, but only after you instruct the DBI not to do anything in case of errors. #!/usr/bin/perl -w use strict; use DBI; # # ---- untested # my ($dns, $user, $password) = ("dbi:wathever:db","me","secret"); my $dbh = DBI->connect($dns,$user,$password, {RaiseError=>0 , PrintError=>0}) # <-- be quiet! or die "can't connect ($DBI::errstr)\n"; my $sth= $dbh->prepare("SELECT WRONG FROM NON_EXISTING"); if ($sth) { # fetch your records while (my $rec = $sth->fetchrow_arrayref()) { print "@$rec\n"; } } else { print "something was wrong: ", $dbh->errstr, "\n"; # d