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 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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.