Chapter 5 — Storing and Sharing Information 85
Connecting to a Database Using DBI and Perl
The DBI module in Perl provides access to database engines through a number of individual
Database Drivers (DBDs). Although you need different DBDs for connecting to different
databases, the basic interface to submitting queries and obtaining results remains the same. The
approach means that you can develop your Google Maps application locally using MySQL but
deploy it using PostgreSQL or Oracle without making any changes to the queries and inter-
faces in the application.
Use CPAN, PPM, or VPM to install DBI and the DBD you need to use for your database environ-
ment. If you are using MySQL, you will need to install DBI and the DBD::mysqlmodule.
To connect to a database through DBI, a data source name (DSN) must be assembled based on
the information required by the DBD driver. For example, to connect to a MySQL database,
you must specify the name of the database and the host on which the database can be found.
To connect to the google_mapsdatabase on the host mysql.mcslp.pri, the DSN would
be DBI:mysql:database=google_maps;host=mysql.mcslp.pri.
The DSN is supplied as an argument to the connectmethod, along with the username and
password if required, to create a new database handle. All queries to the database then use this
database handle as a way of communicating between your application and the MySQL database.
The entire process can be seen more clearly in the stub shown in Listing 5-20.
Listing 5-20: Connecting to a MySQL Database with Perl
#!/usr/bin/perl
use DBI;
my $dbh = DBI-
connect(“DBI:mysql:database=google_maps;host=mysql.mcslp.pri”,’maps’,’maps’);
if ($dbh)
{
print “Connected to database\n”;
}
else
{
print “Couldn’t connect\n”;
}
#Do your stuff
$dbh->disconnect();