This article describes two methods for connecting to a MySQL database using Perl:
- DBI (Database Interface) module
- Legacy mysql module
Connecting to MySQL using the DBI (Database Interface) module
The DBI module is the preferred method for connecting to MySQL in Perl. The original Perl mysql module is no longer supported.
To connect to MySQL using the DBI module, follow these steps:
- Use the following Perl code to connect to MySQL and select a database. Replace username with your username, password with your password, and dbname with the database name:
use DBI; $myConnection = DBI->connect("DBI:mysql:DBNAME:localhost", "USERNAME", "PASSWORD");
-
You can conduct SQL queries and other operations after the code connects to MySQL and selects the database. For instance, the Perl code below executes a SQL query that extracts the last names from the employees database and stores the results in the $result variable:
$query = $myConnection->prepare("SELECT lastname FROM employees"); $result = $query->execute();
Connecting to MySQL using the legacy mysql module
The original Perl mysql module is deprecated and should only be used for backward compatibility. If feasible, use the DBI module instead.
To connect to MySQL using the legacy mysql module, follow these steps:
- Use the following Perl code to connect to MySQL and select a database. Replace username with your username, password with your password, and dbname with the database name:
use Mysql; $myConnection = Mysql->connect('localhost','DBNAME','USERNAME','PASSWORD');
-
You can conduct SQL queries and other operations after the code connects to MySQL and selects the database. For instance, the Perl code below executes a SQL query that extracts the last names from the employees database and stores the results in the $result variable:
$result = $myConnection->query('SELECT lastname FROM employees');