Chapter 12. 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). This chapter was written 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, how to run SQL statements, and how to effectively retrieve data from MySQL using Perl and DBI. For the examples here, the scenario of a bookstore's inventory is used.

Using Perl DBI with MySQL

This section presents basic tasks that you can perform with Perl DBI.

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 script:

#!/usr/bin/perl -w
use strict;
use DBI;
   
my $dbh = DBI->connect ("DBI:mysql:bookstore:localhost",
                        "username","password")
          or die "Could not connect to database: "
          . DBI->errstr;

The first two lines start Perl and set a useful condition for reducing scripting 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 ...

Get MySQL in a Nutshell 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.