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",
          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 DBI module. The next statement (spread over more than one line here) sets up a database handle that specifies the database engine (mysql), the name of the database (bookstore), the hostname (localhost), the username, and the password. Incidentally, the name of the database handle doesn’t have to be called $dbh—anything will do. Next, the or operator provides alternate instructions to be performed if the connection fails. That is, the program will terminate (die) and then display the message in quotes along with whatever error message is generated by the driver using the errstr method from the DBI—the dot (.) merges them together.

Executing an SQL Statement

Making a connection to MySQL does little good unless an SQL statement is executed. Any SQL statement that can be entered from the

Get MySQL in a Nutshell, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.