http://www.perlmonks.org?node_id=1005643

gepebril69 has asked for the wisdom of the Perl Monks concerning the following question:

Hi there,

I'm using DBI to connect to an MySQL database to report statuses from several machines. This works excellent except for some occasions. It seems DBI crashes on opening without producing an error, or am I using wrong code.

I don't want to use the die option as I like to close things myself and take action if neccesary

# Connect to MySQL server $Dbh = DBI->connect($DSN, $Config{'MYSQL_USER'}, $Config{'MYSQL_PASSWD +'}, { PrintError => 0, RaiseError => 0 }); if ($DBI::err) { if ($Dbh) { $Dbh->disconnect} print "Error! we had an error connecting to CMS DB: ".$DBI::errstr; + } # continue code

Thanks in advance

Albert

Replies are listed 'Best First'.
Re: DBI can't catch error
by mje (Curate) on Nov 26, 2012 at 13:27 UTC

    If you fail to connect $Dbh will be undef. If $Dbh is not undef, you connected. So check $Dbh not $DBI::err.

      ok, that easy.

      So simplified it will be something like

      # Connect to MySQL server $Dbh = DBI->connect($DSN, $Config{'MYSQL_USER'}, $Config{'MYSQL_PASSWD +'}, { PrintError => 0, RaiseError => 0 }); # Check if connect went ok if (defined ($Dbh)) { # Good print "Successful connection with DB"; } else { # Problem! print "We had an error connecting to DB: ".$DBI::errstr; exit; }