Perl Dbi Sth Execute Error
Contents |
login Username: * Password: * Create new accountRequest new password Home » DBI: handling database errors ( categories: databases ) Basically, there are
Perl Dbi Execute Error Handling
two ways of handling database errors, check (almost) every DBI call for errors perl dbi execute return value or set 'RaiseError' attribute to '1ยด: -- Manual checking This way, you have to add code yourself to check for
Perl Dbi Handleerror
database error conditions, so 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' perl dbi connect error handling and 'errstr'. 'err' returns the native 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 )
perl dbi errstr {
die "ERROR! return code: . $sth->err . " 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 H
Related Modules Rose::DB::Object DBIx::Class Class::DBI more... By perlmonks.org CPAN RT New 14
Perl Dbi Try Catch
Open 11 Stalled 4 View/Report Bugs Module Version: 1.636 perl dbi error string Source NAME SYNOPSIS GETTING HELP General Mailing Lists IRC Online Reporting
Try Catch In Perl
a Bug NOTES DESCRIPTION Architecture of a DBI Application Notation and Conventions Outline Usage General Interface Rules & Caveats Naming Conventions and http://www.perlhowto.com/dbi_handling_database_errors 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 http://search.cpan.org/perldoc?DBI $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_OF_FIEL
Go to comments The DBI module lets you handle errors yourself if you don't like its built-in behavior. DBI lets you handle the errors at either the database or the statement handle level by specifying attributes: https://www.effectiveperlprogramming.com/2010/07/set-custom-dbi-error-handlers/ my $dbh = DBI->connect( ..., ..., \%attr ); my $sth = $dbh->prepare( ..., \%attr ); http://zetcode.com/db/mysqlperl/err/ 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 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 perl dbi 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 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"; perl dbi execute } 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', '', '', { ShowErrorStatement => 1, } ); The error message shows the SQL statement, but the program still continues: DBD::SQLite::st execute failed: called with 2 bind variables when 1 are needed [for Statement "SELECT * FROM Cats WHERE id = ?"] at dbi-test.pl line 12. Got to the end The RaiseError attribute turns errors into fatal errors that you can trap with eval { ... } or Try::Tiny (Item 103: Handle Exceptions Properly) (or not trap if you want your program to die): # The rest of the program is the same my $dbh = DBI->connect( 'dbi:SQLite:dbname=test.db', '', '', { RaiseError => 1, ShowErr
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 dealin