Chapter 18. Perl API
The easiest method of connecting to MySQL with the programming language Perl is to use the Perl DBI module, which is part of the core Perl installation. You can download both Perl and the DBI module from CPAN (http://www.cpan.org). I wrote this chapter with the assumption that the reader has Perl installed along with DBI.pm and that the reader has a basic knowledge of Perl. Its focus, therefore, is on how to connect to MySQL, run SQL statements, and effectively retrieve data from MySQL using Perl and DBI. This chapter begins with a tutorial on using Perl with MySQL. That’s followed by a list of Perl DBI methods and functions used with MySQL, with the syntax and descriptions of each and examples for most. The examples here use the scenario of a bookstore’s inventory.
Using Perl DBI with MySQL
This section presents basic tasks that you can perform with Perl DBI. It’s meant as a simple tutorial for getting started with the Perl DBI and MySQL.
Connecting to MySQL
To interface with MySQL, first you must call the DBI module
and then connect to MySQL. To make a connection to the
bookstore database using the Perl DBI, only the
following lines are needed in a Perl program:
#!/usr/bin/perl -w
use strict;
use DBI;
my $dbh = DBI->connect ("DBI:mysql:bookstore:localhost","russell",
"my_pwd1234")
or die "Could not connect to database: "
. DBI->errstr;The first two lines start Perl and set a useful condition for
reducing programming errors (use strict). The third line calls the ...