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 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 script 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 mysql client may be executed through the API. Continuing the previous example, let’s look ...