Databases Reference
In-Depth Information
Finally, we can modify problem-handling behavior by setting the attributes
PrintError and RaiseError in the call to the connect( ) function. Setting the
PrintError attribute to 1 displays error messages; setting it to 0 disables this. Similarly,
setting the RaiseError attribute to 1 displays an error message and stops processing if
an error occurs; setting it to 0 disables this. If both are set to 0 , no error messages are
displayed, and the program tries to continue even if the connection to the MySQL
database could not be established. We can use this setting to suppress the default Perl
messages and display only our own custom messages:
my $dbh=DBI->connect("DBI:mysql:host=localhost;database=mysql", " the_username ",
" the_password ", {PrintError=>0, RaiseError=>0})
or
die("Failed connecting to the database");
By default, PrintError is 1 and RaiseError is 0 .
The DBI module includes the special variables $DBI::err and $DBI::errstr to store
information if a problem occurs. These contain, respectively, the error code and human-
readable error message returned by the database server. The two colons are a Perl con-
vention for separating the name of a package (in this case, DBI ) from the name of a
variable defined in the package ( err and errstr ).
We can use these variables in our own error-handling code. For example, we can write:
my $dbh=DBI->connect("DBI:mysql:host=localhost;database=mysql",
" the_username ",
" the_password ", {PrintError=>0, RaiseError=>0})
or
die("Failed connecting to the database (error number $DBI::err):
$DBI::errstr\n");
If RaiseError is set to 1 , a failure to connect to the database might produce the error
message:
DBI connect('host=localhost;database=mysql','root',...) \
failed: Can't connect to local MySQL server through socket \
'/var/lib/mysql/mysql.sock' (2) at ./select.pl line 5
whereas our custom error message above would be displayed as:
Failed connecting to the database (error number 2002): \
Can't connect to local MySQL server through socket \
'/var/lib/mysql/mysql.sock' (2)
While detailed error messages are very useful when debugging code under develop-
ment, it's generally prudent to hide errors from your users in production code, espe-
cially in applications that are published to the Web. Instead, have the program log error
messages to a file or email them to you. That way, users aren't exposed to unsightly
and possibly confusing error messages, and the internals of your system are not as
exposed to potential attackers. When your program does encounter a problem, display
a generic error message such as “We are experiencing technical difficulties; please con-
tact the system administrator or try again later.”
 
Search WWH ::




Custom Search