Databases Reference
In-Depth Information
database=mysql",
" the_username ",
" the_password ");
Don't add a new line before the database=mysql parameter; we had to do this so that
the instruction would fit on the page. If you followed our XAMPP installation instruc-
tions in “Installing Perl modules under Mac OS X” in Chapter 2 to create a symbolic
link to the default MySQL socket file location ( /tmp/mysql.sock ), you can omit the
mysql_socket parameter.
We can follow this with Perl instructions to carry out the main functions of the script.
Finally, being good citizens, we disconnect from the server before we end the script:
$dbh->disconnect();
The arrow ( arrow -> operator ) operator is used to call functions that are associated
with a class of objects. In the connection code, we've called on the connect( ) function
of the DBI class. We also call on functions associated with the database handler and the
statement handler in the same way. We don't describe object-oriented design and pro-
gramming in detail in this topic.
Handling Errors When Interacting with the Database
If the connection to the database fails, the dbh variable will contain an undefined (ef-
fectively 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.");
 
Search WWH ::




Custom Search