Perl: Connecting to MySQL

Connecting and manipulating MySQL

Published: Sunday, 28 March 2004

This article describes how to install the appropriate modules so that a Perl script can connect to a MySQL database, and basic scenarios for data manipulation.

Install necessary modules

Please visit see our page on installing modules.

Install module DBI

The DBI module must first be installed. This is the Perl Database Interface, and provides a standard way to access many databases. To test if this is already installed you can search for the file called DBI.pm, or add the line use DBI; to your script and see if it works. Otherwise, you can download it from the cpan.org modules site. Look for files starting with DBI.

In conjunction with the DBI module you’ll also need drivers. These come in the form of modules starting with DBD-.

Install module DBD::mysql

Look for files starting with DBD-mysql. There seems to be 2 branches. If your target production system is still using 2.10xx, then stick with that branch or even that specific version. Otherwise go for the latest 2.90x version. Read the ChangeLog if you are upgrading from the 2.10x version, as there are some behavioural changes that may affect existing code.

Connecting and manipulating data

Use perldoc DBD::mysql to display basic help.