Speeding up Database Access with mod_perl
There are dozens (perhaps hundreds) of databases on the market, some of which run under Linux. One product which I have used, both in my own consulting work and in the pages of this column, is MySQL, a “mostly free” database (in the author's words) distributed by TcX DataKonsult AB. The “Resources” sidebar contains information on where you can download the source and binaries for MySQL.
The CGI programs we wrote in our previous encounters with MySQL used the Mysql module for Perl, which gives us access to all of MySQL's features. Mysql.pm continues to work just fine for most applications.
However, if you are interested in keeping up with the latest standards and trends within the Perl community, you should switch (as I have) to DBI, the generic database interface for Perl programs. DBI allows you to use the same code on any number of databases. That is, you can write a program that talks to MySQL, Sybase, Oracle or any other database product—and you will have to change only one word in order to port the program to another database product. This makes Perl a very powerful and portable database-access language.
DBI is divided into two parts: the generic DBI module engine, which can be downloaded from CPAN, the Comprehensive Perl Archive Network, and a DBD (database driver) for the particular brand of database you wish to access. There is only one DBI module, but there is a different DBD for each database you might wish to access. (See “Resources” for information on where you can obtain DBI and DBDs.) If you plan to use more than one database server, you will have to install more than one DBD. You can install as many DBDs as you want; they are installed in parallel, and thus do not conflict.
If you are using MySQL, then you will have to download the driver for Msql, the database on whose interface the MySQL API was modeled. Before it compiles and installs the necessary modules, the Msql-modules package asks whether you want to install DBDs for Msql, MySQL or both.
Once you have installed DBI and the appropriate DBD, you will be able to do just about everything you would normally expect from a database. The syntax is a bit different from the syntax we have seen in previous installments of “At the Forge”, but is conceptually quite similar. It should not take you very long to start using DBI, once you have seen some examples.
Connections to the database are kept in a database handle, normally stored in a variable called $dbh. The database handle not only gives you a compact, object-oriented way to access database methods, but also means that you can connect to multiple databases at the same time, giving each connection its own database handle. (This might be useful when moving information from Sybase to Oracle, for example.)
The basic syntax is fairly straightforward:
$dbh = DBI->connect($data_source, $username, $password);
As you can see, the connect method takes three arguments. The first, $data_source, defines the database you wish to access, as well as the name of the computer on which the server sits and the access port on that computer. The second two arguments are theoretically optional, but most configurations will (and should) require them.
For example, most test programs on my home computer use the following syntax:
$dbh = DBI->connect("DBI:mysql:test:localhost");
Because I use the unprotected “test” database, no user name or password is necessary. A production site on which user names and passwords are required would use syntax like the following:
$dbh = DBI->connect("DBI:mysql:classifieds:dbserver", "classy" "51haf3");In the above line of code, we are again connecting with the MySQL DBD. But this time, we are connecting to the database named classifieds on a machine named dbserver, with the username classy and password 51haf3. Remember that user names and passwords on database systems are unrelated to user names and passwords on UNIX systems. For security purposes, you should use different passwords (and perhaps even different user names) with your databases than are actually in use on your system.
If the connection succeeds, $dbh can be used as an entry point into the database. If the connection fails, $dbh remains undefined. This allows us to use the following error-checking code:
&log_and_die($DBI::errstr) unless $dbh;
The &log_and_die routine is one of my old favorites (and probably familiar to long-time readers of this column), printing an error message on the screen and then exiting gracefully. Complete listings including the subroutine &log_and_die are available at ftp://ftp.linuxjournal.com/pub/lj/listings/issue52/2991.tgz.
Now that we are connected to the database server, we can feed it one or more queries in SQL, Structured Query Language.
If we want to insert a value into a table in the database, we can simply say something like:
$sql = "INSERT INTO test_insert (contents) VALUES (\"$random\") ";
Putting the SQL query into a scalar variable before using it is not required, but helps if and when you need to debug the code. (This way, you can easily add a “print” statement in the middle of your program.)
With the query all set, we tell the database to perform the requested action using the do method. This returns a variable which I call $successful_insert; much like $dbh, $successful_insert is defined only if the query was successful:
$successful_insert = $dbh->do($sql); print "<P>Success!</P>\n" if $successful_insert;
Finally, we disconnect from the database. This is not completely necessary, since Perl will close connections when we are no longer using them. Nevertheless, it is always a good programming practice to clean up:
$dbh->disconnect;The above syntax is good for any SQL query from which we do not expect a result, namely INSERT, DELETE and UPDATE. (For more information about SQL, see Resources for some book recommendations.)
Webinar: 8 Signs You’re Beyond Cron
11am CDT, April 29th
Join Linux Journal and Pat Cameron, Director of Automation Technology at HelpSystems, as they discuss the eight primary advantages of moving beyond cron job scheduling. In this webinar, you’ll learn about integrating cron with an enterprise scheduler.Join us!
- March 2015 Issue of Linux Journal: High-Performance Computing
- Not So Dynamic Updates
- April 2015 Video Preview
- Users, Permissions and Multitenant Sites
- New Products
- Flexible Access Control with Squid Proxy
- Security in Three Ds: Detect, Decide and Deny
- Non-Linux FOSS: MenuMeters
- DevOps: Everything You Need to Know
- Tighten Up SSH