May 19, 2010

f Comment

Perl DBI: How Do I Disable Printing Errors?

Amazon I am using Perl DBI module to communicate with a database. How do I turn off or disable error printing so that I don't show errors on the screen when they occur?

Surprisingly this simple question is not well answered on the web, so I am answering this question now. In DBI's connect() function you can specify options. The options that affect error handling are RaiseError and PrintError. To disable printing error on the screen, you set them both to 0:

RaiseError => 0,
PrintError => 0

Create a hash called 'options' and put these key value pairs in it:

%options = ( "RaiseError", 0, "PrintError", 0);
Then run the Perl code to connect to a database:

$dbh = DBI->connect( "dbi:mysql:$database:localhost:3306", "username", "password", %options);
Then when an error occurs during any DBI operation, you won't see any error on screen. When an error occurs, the appropriate error message will also be populated in $DBI::errstr. So you can use the following code to know whether an error has occurred:

if($DBI::errstr) {
# an error has occurred; log the value of $DBI::errstr
}

If you get a handle out of executing some operation, then you can also use that handle to detect an error:

$dbh = DBI->connect( "dbi:mysql:$database:localhost:3306", "username", "password", %options);
if($dbh) {
# connection succeeds!
} else {
# connection failed..
}

Hope it helps! Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael