Connecting to MySQL with the DBI

With the architecture installed, we will start by writing a Perl program that uses DBI to connect to the MySQL database.

Perl communicates with MySQL using a database handle. The connect() method uses a general format:

$dbh = DBI->connect($data_source, $username, $auth [, %attr]);

So we may use this format:

$dbh = DBI->connect("DBI:mysql:$db_name:hostname:port", $db_user, $db_pass);

or with additional parameters:

$dbh = DBI->connect("DBI:mysql:$db_name:hostname:port", $db_user, $db_pass,
  { RaiseError => 1, PrintError => 0 } );

where $dbh is the database handle returned (if connection is successful), and the parameters are used like this:

  • $db_name holds the name of the database to connect to.

  • hostname is the ...

Get Sams Teach Yourself MySQL in 21 Days, Second Edition now with O’Reilly online learning.

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