Database Reference
In-Depth Information
Perl
The DBI module provides two attributes that control what happens when DBI method
invocations fail:
PrintError , if enabled, causes DBI to print an error message using warn() .
RaiseError , if enabled, causes DBI to print an error message using die() . This
terminates your script.
By default, PrintError is enabled and RaiseError is disabled, so a script continues
executing after printing a message if an error occurs. Either or both attributes can be
specified in the connect() call. Setting an attribute to 1 or 0 enables or disables it,
respectively. To specify either or both attributes, pass them in a hash reference as the
fourth argument to the connect() call.
The following code sets only the AutoCommit attribute and uses the default settings for
the error-handling attributes. If the connect() call fails, a warning message results, but
the script continues to execute:
my $conn_attrs = { AutoCommit => 1 };
my $dbh = DBI -> connect ( $dsn , "baduser" , "badpass" , $conn_attrs );
Because you really can't do much if the connection attempt fails, it's often prudent to
exit instead after DBI prints a message:
my $conn_attrs = { AutoCommit => 1 };
my $dbh = DBI -> connect ( $dsn , "baduser" , "badpass" , $conn_attrs )
or exit ;
To print your own error messages, leave RaiseError disabled and disable PrintError
as well. Then test the results of DBI method calls yourself. When a method fails, the
$DBI::err , $DBI::errstr , and $DBI::state variables contain the MySQL error num‐
ber, a descriptive error string, and the SQLSTATE value, respectively:
my $conn_attrs = { PrintError => 0 , AutoCommit => 1 };
my $dbh = DBI -> connect ( $dsn , "baduser" , "badpass" , $conn_attrs )
or die "Connection error: "
. "$DBI::errstr ($DBI::err/$DBI::state)\n" ;
If no error occurs, $DBI::err is 0 or undef , $DBI::errstr is the empty string or un
def , and $DBI::state is empty or 00000 .
When you check for errors, access these variables immediately after invoking the DBI
method that sets them. If you invoke another method before using them, DBI resets
their values.
If you print your own messages, the default settings ( PrintError enabled, RaiseEr
ror disabled) are not so useful. DBI prints a message automatically, then your script
Search WWH ::




Custom Search