How to connect to MySQL using Perl

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:

  1. 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");
    
  2. 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:

  1. 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');
    
  2. 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');
Was this answer helpful?

Related Articles

How to connect to MySQL from the command line

This article will show you how to use the mysql program to connect to MySQL from the command...

How to connect to MySQL using Node.js

This article demonstrates how to connect to a MySQL database using Node.js. Connecting to MySQL...

How to connect to MySQL using PHP

This article describes several methods to connect to a MySQL database using PHP: MySQL...

How to connect to MySQL using Python

Python provides several ways to connect to a MySQL database and process data. This article...

How to convert a MySQL database to UTF-8 encoding

This article explains how to convert the character set of a MySQL database to UTF-8 encoding...