Dbi Prepare Error
Contents |
login Username: * Password: * Create new accountRequest new password Home » DBI: handling database errors ( categories: databases ) Basically, there are two ways of
Perl Dbi Prepare
handling database errors, check (almost) every DBI call for errors or set 'RaiseError' perl dbi prepare vs prepare_cached attribute to '1ยด: -- Manual checking This way, you have to add code yourself to check for database error conditions, so
Perl Dbi Prepare Multiple Statements
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 dbi prepare execute 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 . perl dbi autocommit " 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 rights reserved
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta
Dbi Bind_columns
Discuss the workings and policies of this site About Us Learn more perl dbi execute error handling about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack
Perl Dbi Handleerror
Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping http://www.perlhowto.com/dbi_handling_database_errors each other. Join them; it only takes a minute: Sign up Error handling on DBI->connect up vote 2 down vote favorite 1 Besides handling error using standard code die "Unable to connect: $DBI::errstr\n" is it possible to write a custom code like below? Standard: $dbstore = DBI->connect($dsn, $user, $pw, {ora_session_mode => $mode, PrintError => 0, RaiseError => http://stackoverflow.com/questions/6649456/error-handling-on-dbi-connect 0, AutoCommit => 0}) or die "Unable to connect: $DBI::errstr\n"; Custom: $dbstore = DBI->connect($dsn, $user, $pw, {ora_session_mode => $mode, PrintError => 0, RaiseError => 0, AutoCommit => 0}); if (!$dbstore) { CUSTOM_LOG_HANDLER("Could not connect to database: $DBI::errstr"); return; } Sample Standard Code: #!/usr/bin/perl # PERL MODULES WE WILL BE USING use DBI; use DBD::mysql; # HTTP HEADER print "Content-type: text/html \n\n"; # CONFIG VARIABLES $platform = "mysql"; $database = "store"; $host = "localhost"; $port = "3306"; $tablename = "inventory"; $user = "username"; $pw = "password"; #DATA SOURCE NAME $dsn = "dbi:mysql:$database:localhost:3306"; # PERL DBI CONNECT (RENAMED HANDLE) $dbstore = DBI->connect($dsn, $user, $pw) or die "Unable to connect: $DBI::errstr\n"; Thanks for you time. perl dbi share|improve this question asked Jul 11 '11 at 11:30 Hozy 1031210 Are there any other ways to exit gracefully without errors getting logged into the web server logs? –Hozy Jul 11 '11 at 11:37 add a comment| 1 Answer 1 active oldest votes up vote 12 down vote accepted You can always use a
Related Modules Rose::DB::Object DBIx::Class Class::DBI more... By perlmonks.org CPAN RT New 14 Open http://search.cpan.org/perldoc/DBI 11 Stalled 4 View/Report Bugs Module Version: 1.636 Source NAME SYNOPSIS GETTING HELP General Mailing Lists IRC Online Reporting a Bug http://zetcode.com/db/mysqlperl/err/ NOTES DESCRIPTION Architecture of a DBI Application Notation and Conventions Outline Usage General Interface Rules & Caveats Naming Conventions and Name Space SQL perl dbi - 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::errstr $DBI::state $DBI::rows perl dbi prepare $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_OF_FIELDS NUM_OF_PARAMS NAME NAME_lc NAME_uc NAME_hash NAME_lc_hash NAME_uc_hash
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() $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 = "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 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 true. #!/usr