Handling Errors When Interacting with the Database
If the connection to the database fails, the dbh
variable will contain an undefined
(effectively false) value. We should test for this and stop the
program if the connection failed; otherwise, we’ll run into
difficulties once the program tries to use the database, generating
unhelpful error messages such as:
Can't call method "prepare" on an undefined value at ./select.pl line 9.
One way to test for connection failure is simply to check the value of the database handler variable:
my $dbh=DBI->connect("DBI:mysql:host=localhost;database=$DB_Database", "$DB_Username", "$DB_Password"); if(!$dbh) { die("Failed connecting to the database."); }
If the database handler is not valid, we use the die()
function to print an error message
and stop the program.
A more compact way is to use the or
keyword to execute the die()
function if the connection
failed:
my $dbh=DBI->connect("DBI:mysql:host=localhost;database=$DB_Database", "$DB_Username", "$DB_Password") or die("Failed connecting to the database.");
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 ...
Get Learning MySQL now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.