# Connecting to MySQL using Perl

> Connect a Perl script to a MySQL database using the DBI module or the older mysql module, with example code for each.

Source: https://helpcenter.ruachost.com/developers/databases/connecting-to-mysql-using-perl/

**Connecting to MySQL using Perl**\
This article explains two methods for connecting to a MySQL database using Perl: the DBI (Database Interface) module and the legacy mysql module.

**Tip:** MySQL databases and users must already exist before using these methods.

**Using the DBI (Database Interface) module**\
The DBI module is the recommended way to connect to MySQL in Perl. The legacy mysql module is deprecated.

Example code to connect and select a database (replace `USERNAME`, `PASSWORD`, and `DBNAME` with your details):

```
use DBI;
$myConnection = DBI->connect("DBI:mysql:DBNAME:localhost", "USERNAME", "PASSWORD");
```

After connecting, you can run SQL queries. For example, to select last names from the `employees` table:

```
$query = $myConnection->prepare("SELECT lastname FROM employees");
$result = $query->execute();
```

**Using the legacy mysql module**\
The original Perl mysql module is deprecated and should only be used for backward compatibility.

Example code to connect and select a database (replace `USERNAME`, `PASSWORD`, and `DBNAME`):

```
use Mysql;
$myConnection = Mysql->connect('localhost','DBNAME','USERNAME','PASSWORD');
```

After connecting, run SQL queries. For example:

```
$result = $myConnection->query('SELECT lastname FROM employees');
```

**More information**\
For details about the DBI module, visit [DBI Documentation](http://dbi.perl.org/docs).
