Perl Dbi Sth 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 execute error handling handling database errors, check (almost) every DBI call for errors or set 'RaiseError'
Perl Dbi Execute Return Value
attribute to '1ยด: -- Manual checking This way, you have to add code yourself to check for database error conditions, so perl dbi handleerror 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
Perl Dbi Connect Error Handling
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 errstr " 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
Q&A Tutorials Poetry 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.
Perl Dbi Try Catch
And just as you should always check the return code of your system calls, so should
Perl Dbi Error String
you always check the return status of your database calls. The easiest way to do this is by setting DBI's RaiseError attribute to try catch in perl 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 http://www.perlhowto.com/dbi_handling_database_errors 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, eg.: http://www.perlmonks.org/?node_id=7568 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 to associate any attributes with this particular method,
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and http://stackoverflow.com/questions/6649456/error-handling-on-dbi-connect policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags http://www.perl.com/pub/1999/10/DBI.html Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join them; it only takes perl dbi 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 => 0, AutoCommit => 0}) or die "Unable to connect: $DBI::errstr\n"; Custom: perl dbi execute $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 custom error handler with the DBI: #!/usr/bin/perl use strict; use warnings; use DBI; sub handle_error { my $message = shift; #write er
databases started to get to be a big deal in the 1970's, andthey're still a big deal today, which is a little peculiar, because they're a 1960's technology. A relational database is a bunch of rectangular tables. Each row of a table is a record about one person or thing; the record contains several pieces of information called fields. Here is an example table: LASTNAME FIRSTNAME ID POSTAL_CODE AGE SEX Gauss Karl 119 19107 30 M Smith Mark 3 T2V 3V4 53 M Noether Emmy 118 19107 31 F Smith Jeff 28 K2G 5J9 19 M Hamilton William 247 10139 2 M The names of the fields are LASTNAME, FIRSTNAME, ID, POSTAL_CODE, AGE, and SEX. Each line in the table is a record, or sometimes a row or tuple. For example, the first row of the table represents a 30-year-old male whose name is Karl Gauss, who lives at postal code 19107, and whose ID number is 119. Sometimes this is a very silly way to store information. When the information naturally has a tabular structure it's fine. When it doesn't, you have to squeeze it into a table, and some of the techniques for doing that are more successful than others. Nevertheless, tables are simple and are easy to understand, and most of the high-performance database systems you can buy today operate under this 1960's model. About SQL SQL stands for Structured Query Language. It was invented at IBM in the 1970's. It's a language for describing searches and modifications to a relational database. SQL was a huge success, probably because it's incredibly simple and anyone can pick it up in ten minutes. As a result, all the important database systems support it in some fashion or another. This includes the big players, like Oracle and Sybase, high-quality free or inexpensive database systems like MySQL, and funny hacks like Perl's DBD::CSV module, which we'll see later. There are four important things one can do with a table: SELECT Find all the records that have a certain property
INSERT Add new records DELETE Remove old records UPDATE Modify records that are already there Those are the four most important SQL commands, also called queries. Suppose that the example table above is named people. Here are examples of each of the four important kinds of queries: SELECT firstname FROM people WHERE lastname = 'Smith' (Locate the first names of all the Smiths.) DELETE FROM people WHERE id = 3 (Delete Mark Smith