Parag Kalra <paragka...@gmail.com> asked:
[DBI]
> However I just wanted to know if there is a way to catch this error
> message through some standard DBI variable so that I can print it in a log 
> file

You can use the errstr() class and instance methods to access the last error 
message.

In order to stop DBI from printing a warning message on error, you'll have to 
set the  PrintError attribute to 0.

Minimal untested example:

#!/usr/bin/perl -w

use strict;
use DBI;

# DB connection details go here
my $db_name = '<database>';
my $db_host = '<host>';
my $db_user = '<user>';
my $db_pass = '<password>';
# RaiseError => 0 and AutoCommit => 1 are actually defaults which are only
# provided here in case you want to quickly set them to different values
# for testing purposes.
my $db_options = { RaiseError => 0, PrintError => 0, AutoCommit => 1 };

my $dsn = "dbi:mysql:$db_name" . ( $db_host ne "" ? ";host=$db_host" : "" );

# invoke DBI class method errstr() on error
my $dbh = DBI->connect($dsn, $db_user, $db_pass, $db_options ) or die "Can't 
connect to MySQL server: " . DBI->errstr;

if( defined( $dbh->do( <sonmething> ) ){
  # all went well, proceeed normally
} else {
  # an error occurred - use $dbh->errstr() here to access the error message.
  # this silly example is equivalent to using attribute RaiseError = 1
  die "database error: " . $dbh->errstr()
}

__END__

HTH,
Thomas

Reply via email to