In this conclusion to a four-part series on Perl and DBI, you will learn about SQL queries and DBI, using Perl and DBI with CGI, and more. This article is excerpted from chapter 15 of the book Beginning Perl (Apress; ISBN: 159059391X).
In addition to the preceding SQL commands, another topic that is important to know is indexing a table. This can significantly increase the speed ofSELECT statements on large tables. See the docs for more information.
Speaking of seeing the docs for more information on SQL, as a reminder, be sure to check out the online documentation for MySQL at http://dev.mysql.com/doc/mysql/en/ and the excellent book The Definitive Guide to MySQL, Second Edition by Michael Kofler.
In this chapter we described how we can access a database using Perl and the DBI module. We started with a description of a relational database and followed that with a brief introduction to SQL.
We then installed MySQL and created a database with three tables. We talked about several SQL commands:INSERTandSELECT were the most important ones. Table joins were discussed as a way to implement the relations in relational databases.
Then we introducedDBIandDBD::mysql, and wrote several Perl scripts to access and query the database.
We ended with an example of how easy it is to create dynamic web content by connecting Perl,DBI, andCGI.pm. And in the middle of that discussion we took time out of our busy day to call one of our favorite musicians.
Write a Perl script that prompts the user for an instrument and then prints all the musicians that play that instrument.
Write a CGI program similar to musicians.pl that is a web interface to the script you created for exercise 1.
1. These arenít their real phone numbers. Sorry about that.
3. This is a very bad password for many reasons, the least of which is that it is published in this book. For information on creating good passwords, see Hacking Linux Exposed, Second Edition, Brian Hatch, Osborne Press (2002).
4. This MySQL stuff is easy!
5. Another bad password, but a snippet of lyric from a great song.
6. TMTOWTDI in SQL too!
7. As usual, there are a lot of ways to execute an SQL query and retrieve its results using Perl and DBI. We will look at the easiest and most common way, but you can read about all the various ways by typing perldoc DBI at the shell prompt.