Perl Catch Mysql Error
Contents |
RecentThreads NewestNodes Donate What'sNew on Mar 08, 2005 at 15:16UTC ( #437578=perlquestion: print w/replies, xml ) Need Help?? svenXY has asked for the wisdom of the Perl Monks concerning the following question: Hi All, In contrary to all perl dbi handleerror documentation I was capable of, I wasn't able to catch a DBI
Perl Dbi Error Handling Examples
error to replace it with another message. I can get the error message into a varialbe, but cannot perl dbi connect error handling prevent DBI from displaying the error again. Here's some sample code: use DBI; my $dbh = DBI->connect("DBI:mysql:database=www;host=myhost.domain.com: +3306;user=auser;password=apwd", {RaiseError => 1, PrintError => 0}); my $sql = 'select wrong_col, correct_col from
Perl Dbi Execute Return Value
table limit 10'; my $hash_ref; print "Trying HandleError (with RaiseError on):\n"; $hashref = $dbh->selectall_hashref($sql, 'filename', {RaiseError => 1, PrintError => 1, HandleError => \&handle_error() +}); print "Trying RaiseError and eval:\n"; eval{ $hashref = $dbh->selectall_hashref($sql, 'filename', {RaiseError => 1, PrintError => 0}); }; if ($@) { print "\tEval found: $@\n"; } my $sth = $dbh->prepare($sql); print "Trying Errstr:\n"; $sth->execute(); if ($dbh->errstr) perl dbi errstr { print "\tErrstr: " .$dbh->errstr . "\n"; } sub handle_error { # my $error = shift; print "\tSub 'handle_error': $error\n"; print "\tEnd sub\n"; } [download] As a result, I get: $ perl tester.pl Trying HandleError (with RaiseError on): Sub 'handle_error': End sub DBD::mysql::db selectall_hashref failed: Unknown column 'wrong_col' in + 'field list' at tester.pl line 11. Trying RaiseError and eval: DBD::mysql::db selectall_hashref failed: Unknown column 'wrong_col' in + 'field list' at tester.pl line 16. Trying Errstr: DBD::mysql::st execute failed: Unknown column 'wrong_col' in 'field li +st' at tester.pl line 26. Errstr: Unknown column 'wrong_col' in 'field list' - or - when redirecting STDERR: $ perl tester.pl 2>/dev/null Trying HandleError (with RaiseError on): Sub 'handle_error': End sub Trying RaiseError and eval: Trying Errstr: Errstr: Unknown column 'wrong_col' in 'field list' [download] Basically, the error message is printed to STDERR on all three tests, I was never able to prevent it. Second, the error was caught by handle_error, but the error message was not handed over as it should be. The third way worked OK, except that it did print the error message to S
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 company Business
Perl Dbi Try Catch
Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs
Try Catch In Perl
Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just perl dbi example like you, helping 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 http://www.perlmonks.org/?node_id=437578 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: $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; http://stackoverflow.com/questions/6649456/error-handling-on-dbi-connect 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 error message wherever you want print "the message is '$message'\n"; exit; #stop the program } my $dbh = DBI->connect( "dbi:SQLite:foo", "user", "pass", { PrintError => 0, HandleError => \&handle_error, } ) or handle_error(DBI->errstr); my $sth = $dbh->prepare("select * from doesntexist"); That said, you should be logging errors, and for a web application, the web server's logs makes sense. If you are worried about the amount of noise in your web logs, you should concentrate on fixing the errors, not making the logs l
Community Podcasts MySQL.com Downloads Documentation Section Menu: MySQL Forums :: Perl :: Error-handling problem using perl DBI with MySQL New Topic Advanced Search Error-handling problem using perl DBI with MySQL Posted by: Sam http://forums.mysql.com/read.php?51,60081,60081 Wilson () Date: December 16, 2005 06:13AM Error-handling problem using perl DBI with http://www.perlhowto.com/dbi_handling_database_errors MySQL..... The truth is that I don't know if this is a MySQL or DBI issue. Below is my connect string and my insert string. Whenever I run the application with a duplicate entry, the error always gets dumped to the screen as shown below. Can anyone tell me why the or (||) perl dbi isn't being activated on the bad insert? How do I capture the error to return an appropriate response to the user? HELP! Thanks, Sam ### connect $dbh = DBI->connect ("DBI:mysql:host=localhost;database=$db","$dbu", "$dbp",{RaiseError => 1}) || die "Connection to:$db failed: $DBI::errstr\n" ; #### insert my $sqltxt = "INSERT INTO $insert_table ($insert_columns) VALUES ($insert_values) "; my $sth = $dbh->prepare($sqltxt)|| die "Could not prepare SQL statement:$sqltxt"; $sth->execute || die "Could not perl catch mysql execute SQL statement:$sqltxt"; return; } ##### error dump to screen Errors Output DBD::mysql::st execute failed: Duplicate entry 'bert' for key 2 at /line 199. , /usr/perl5/lib/site_perl/5.6.1/Apache/ASP.pm line 1556 Debug Output DBD::mysql::st execute failed: Duplicate entry 'bert' for key 2 at /line199. , /usr/perl5/lib/site_perl/5.6.1/Apache/ASP.pm line 1556 Navigate:Previous Message•Next Message Options:Reply•Quote Subject Written By Posted Error-handling problem using perl DBI with MySQL Sam Wilson 12/16/2005 06:13AM Re: Error-handling problem using perl DBI with MySQL bill 01/12/2006 08:28AM Sorry, you can't reply to this topic. It has been closed. powered by phorum Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party. Contact Sales USA: +1-866-221-0634 Canada: +1-866-221-0634 Germany: +49 89 143 01280 France: +33 1 57 60 83 57 Italy: +39 02 249 59 120 UK: +44 207 553 8447 Japan: 0120-065556 China: 10800-811-0823 India: 0008001005870 More Countries» Contact Us Online» Products MySQL Enterprise Edition MySQL Standard Edition MySQL Classic Edition MySQL Cluster CGE MySQL Embedded (OEM/ISV) Services Training Certification Consulting Support Downloads MySQL Community Server MySQL Cluster MySQL Fabric MySQL Utilities MySQL Workbench
login Username: * Password: * Create new accountRequest new password Home » DBI: handling database errors ( categories: databases ) Basically, there are two ways of handling database errors, check (almost) every DBI call for errors or set 'RaiseError' attribute to '1ยด: -- Manual checking This way, you have to add code yourself to check for 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' 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 )
{
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 Home | Links | RS