Print Dbi Error String
Contents |
Related Modules Rose::DB::Object DBIx::Class Class::DBI more... By perlmonks.org CPAN RT New 14 Open 11 Stalled perl dbi execute error handling 4 View/Report Bugs Module Version: 1.636 Source perl dbi execute return value NAME SYNOPSIS GETTING HELP General Mailing Lists IRC Online Reporting a Bug NOTES DESCRIPTION
Perl Dbi Connect Error Handling
Architecture of a DBI Application Notation and Conventions Outline Usage General Interface Rules & Caveats Naming Conventions and Name Space SQL - A
Perl Dbi Handleerror
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 $DBI::lasth METHODS COMMON TO perl dbi errstr 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 TYPE PRECISION SCALE NULLABLE CursorName Database State
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: my $dbh
Perl Dbi Try Catch
= DBI->connect( ..., ..., \%attr ); my $sth = $dbh->prepare( ..., \%attr ); There are several dbi trace example attributes that affect error handling, each of which you can use with either a connection or a statement handle: Attribute Type Default PrintWarn try catch in perl 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 do just what they say. http://search.cpan.org/perldoc?DBI 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"; } print "Got to the end\n"; Since PrintError https://www.effectiveperlprogramming.com/2010/07/set-custom-dbi-error-handlers/ 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, ShowErrorStatement => 1, } ); use Try::Tiny; try { $sth->prepare( ... ); $sth->execute( ... ); } cat
Poetry RecentThreads NewestNodes Donate What'sNew on Oct 04, 2011 at 18:51UTC ( #929639=perlquestion: print w/replies, xml ) Need Help?? djten has asked for the wisdom of the Perl Monks concerning the following question: This one has got me scratching my head. It involves running some Perl code on http://www.perlmonks.org/?node_id=929639 two computers. One is my desktop computer, running Windows 7 Professional SP1, everything up to date. The other is my laptop computer, running Vista Home Premium SP2, everything up to date. Everything else is the same - http://www.tutorialspoint.com/perl/perl_database.htm I purposely made it so. I set them both up at the same time, in the same way, because I wanted to have as close to identical development environments as possible between working in my office and perl dbi going on the road. ActiveState Perl v5.12.4, Apache v2.2.17, MySQL v5.5.8, Perl DBI v1.616, and all configuration settings identical on both computers. Yesterday I generated an error on my desktop computer in a project I am working on. I had changed a column name in a table, but forgot to update the references to that column in my code. So executing the code generated an error. I have code to display any database access errors, perl dbi execute relying on $DBI::err and $DBI::errstr. In this case the error was of course "unknown column." What I noticed was, when I use my laptop to run the same code on the identically structured table (that still had the column name discrepancy), I got the same error, but where my same error-catching code trys to display the contents of $DBI::err and $DBI::errstr, I get nothing. An empty string, I guess. The error is definitely generated, but $DBI::err and $DBI::errstr are empty. Only on my laptop, with all the same versions of everything. I have an identical copy of all the projects I am working on or maintaining on both computers. So on my desktop I go to a different project, put an error into some database access code, and purposelly generate an error. The err and errstr values show up. Then I make the same purposeful error in the same project on my laptop, and err and errstr are still blank. So it's not specific to one project - I would guess that it is system-wide in some way. But what, where, how? At this point someone will certainly wonder, when did you start noticing this happening on the laptop? Did you install something new on that laptop recently? Well, I just installed both machines last week (identical everyting, as I described above), a
Data Types Perl Variables Perl Scalars Perl Arrays Perl Hashes Perl IF...ELSE Perl Loops Perl Operators Perl Date & Time Perl Subroutines Perl References Perl Formats Perl File I/O Perl Directories Perl Error Handling Perl Special Variables Perl Coding Standard Perl Regular Expressions Perl Sending Email Perl Advanced Perl Socket Programming Perl Object Oriented Perl Database Access Perl CGI Programming Perl Packages & Modules Perl Process Management Perl Embedded Documentation Perl Useful Resources Perl Quick Guide Perl Functions References Selected Reading Developer's Best Practices Computer Glossary Who is Who Perl Database Access Advertisements Previous Page Next Page This tutorial will teach you how to access a database inside your Perl script. Starting from Perl 5 it has become very easy to write database applications using DBI module. DBI stands for Database Independent Interface for Perl which means DBI provides an abstraction layer between the Perl code and the underlying database, allowing you to switch database implementations really easily. The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used. Architecture of a DBI Application DBI is independent of any database available in backend. You can use DBI whether you are working with Oracle, MySQL or Informix etc. This is clear from the following architure diagram. Here DBI is responsible of taking all SQL commands through the API, (ie. Application Programming Interface) and to dispatch them to the appropriate driver for actual execution. And finally DBI is responsible of taking results from the driver and giving back it to the calling script. Notation and Conventions Throughout this chapter following notations will be used and it is recommended that you should also follow the same convention. $dsn Database source name $dbh Database handle object $sth Statement handle object $h Any of the handle types above ($dbh, $sth, or $drh) $rc General Return Code (boolean: true=ok, false=error) $rv General Return Value (typically an integer) @ary List of values re