Main Page Content
An Introduction To The Perl Dbi
Introduction
DBI is a Perl module that makes it possible to use Perl to access
many different types of databases though a single API that worksindependently of the actual database being used. This means that theprogrammer is able to use the DBI module (Database Independent) totalk to a MySQL database, a DB2 database, an Oracle database, and manyothers using the same DBI-specific variables and functioncalls. Although there are also many functions built into the DBI forspecific database engines, the core functionality is always thesame. This functionality makes DBI a very powerful programming tool,but after a brief introduction, you will notice that the DBI is alsovery accessible and easy to understand; programmers require knowledgeof only a few key features to get started writing scripts to performany number of database tasks.How it All Works
There are three tiers within every Perl DBI application. The first
layer is the Perl script itself, which uses the DBI ApplicationProgram Interface (the objects, functions and variables predefined bythe DBI) to interact with the database. The middle layer is the DBI,whose main responsibility is to pass those DBI-specific instructionsto the appropriate database driver. The third layer is the DBD(Database Dependent) layer, which is the driver for the specificdatabase engine you are using.Example: The Postcard Application
Let's say I have a collection of postcards, and in order to keep
them organized, I have entered information about them into a MySQLdatabase. Then let's say that I want to show those postcards off tovisitors to my website. Because I have only CGI available on my webserver, I decide the best way to do that is through a CGIapplication. I start out my application like this:#!/usr/bin/perl -wuse CGI("standard");
use DBI;
This bit of code first specifies this as a Perl script. Then it makes
the Perl CGI module available (this module automates some HTML writingand means less typing). The last line makes available the DBI module.My next step is to define some variables for the database and
connect to it:my $datasource = "DBI:mysql:postcards:localhost";my $user = "greg"my $passwd = "greatpostcards";
If you have ever written any sort of application that has a
database interface, this information should look familiar toyou. However, note that the syntax of the$datasource
variable is a bit unique. The pattern, which seems at first to becounter-intuitive, works like this: DBI:[DBD driver]:[database name]:[database host]
.Remember that DBI applications are designed to easily talk to many
different types of databases. Specifying the type of database youwant to use in your application is as easy as changing a single partof the string held in the$datasource
variable. So, now that all ofmy connection information has been defined, my next step is tocreate a connection object. That's as easy as adding the following to myapplication: my $dbh = DBI->connect($datasource,$user,$passwd);
.The string contained in the $datasource
variable is
Now that I have defined my connection object, my next step is to
prepare an SQL statement. I can do that by using the (you guessed it)prepare method:my $sth = $dbh->prepare("SELECT postcard.*, location.* sender.* FROM postcard LEFT JOIN location ON postcard.location_id = location.location_id, LEFT JOIN sender ON postcard.sender_id = sender.sender_id WHERE postcard.pc_id = ?;");
Now, with the SQL statement prepared, my next step is to execute
it. We do that by employing the execute method:$sth->execute($dynamicvariable);
Everything might seem pretty clear in these two lines, except you
might notice the question mark in the SQL statement and the$dynamicvariable
we pass to it when we invoke the execute method. Thisis a feature of the Perl DBI, which allows me to pass any number ofvariables to my SQL statement before it is executed. The value ofthese variables then fits into the question mark placeholders, inthe order they are passed. (So I should be sure that the variables I pass goin the right order!) If my application does not require me topass dynamic values to my SQL statement, I would have simply called theexecute method without any parentheses, like this: $sth->execute;
Now, for the final step in my application, I need a way of
getting at the contents of the record set that the execute methodreturns. As is always the way with Perl, there are a billion differentways of doing this. But since I'm dealing with rows of data, thefetchrow_array
works well, because it allows me to loop through thereturned row as an array.my @array = $sth->fetchrow_array;my $i;for $i (0..$#array) { print $array[$i],"";}
As I have already mentioned, I have many other DBI
functions at my disposal at this point. Thefetchrow_arrayref
will return the database row as anarray reference. The fetchrow_hashref
will return it as ahash reference (this is especially handy if you have a lot of rows andyou want to key them up by their column names; if you're like me, you tend toremember names better than numeric values). And there are manyothers. Be sure to read the documentation to find the function thatmost suits your needs and programming behaviors.My next step is to clean up my program. Though clearing memory and
closing database connections is not always necessary, it is goodprogramming practice (not to mention easy to do). So I recommendit. Here's all you have to do:$sth->finish;$dbh->disconnect;
Once that's done, I'm done with my postcard
application. But beyond the simple API demonstrated by the codesnippets above, it may not be exactly clear why the Perl DBI isvaluable. Here are some benefits I have found.Why You Might Care About This
- Ubiquity: The Perl DBI module is included with the defaultinstall of any relatively new version of Perl. So if you have accessto a UNIX-based system, you should be able to start programming thePerl DBI.
- Easy Integration: Because it's a Perl module, database functionalitycan be easily integrated into existing Perl/CGI applications.
- Simplicity and Power: being able to talk to a wide variety ofdatabases with Perl (and even within a single Perl script) makesmassive exports and/or imports of data even much more manageable(anyone who has had the job of upgrading a corporate RDBMS can see thevalue in this, I'm sure).
Further Reading and DBI Resources
You can start your search for Perl DBI information just about anywhere
on the web. There is the Database Interfaces section of the CPAN website, there are Perl-orientednewsgroups. However, the best places tostart reading about Perl DBI is either by checking out Symbolstone,the central resource for Perl DBI and DBD modules and documentation onthe Web, or else just running theperldoc DBI
command at your localUNIX prompt. Generally the information is accessible and easy to understand, andwill help you further as you get started.Conclusion
Notwithstanding all of the pitfalls and shortcomings of Perl
programming generally, the power, simplicity, and accessibility of the Perl DBImake it worth understanding. And even though it has the ability towork well with the most complex development projects, it's easyenough to learn in time for your next Web administration crisis as well.