Connecting to MySQL in a Perl Script Using ODBC
When working with Perl and MySQL, one of the most reliable ways to establish a connection is through ODBC (Open Database Connectivity). This approach provides flexibility, as ODBC acts as a bridge between your Perl application and the MySQL database. In this post, we’ll walk through how to set up a simple Perl script that connects to a MySQL database using ODBC.
Prerequisites
Before we start coding, make sure the following are in place:
- Perl installed on your system.
- MySQL ODBC driver configured with a DSN (Data Source Name).
- On Linux/Unix, you can configure this in /etc/odbc.ini.
- On Windows, use the ODBC Data Source Administrator.
- Perl modules:
You can install the modules via CPAN if they aren’t already installed:
cpan DBI
cpan DBD::ODBC
The Perl Script
Here’s a simple Perl script that demonstrates how to connect to a MySQL database using ODBC:
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
# Define the DSN, username, and password
my $dsn = ‘DBI:ODBC:your_dsn_name’;
my $username = ‘your_username’;
my $password = ‘your_password’;
# Connect to the database
my $dbh = DBI->connect($dsn, $username, $password, {
RaiseError => 1,
PrintError => 0,
AutoCommit => 1,
}) or die “Failed to connect: ” . DBI->errstr;
print “Connected to the database successfully!\n”;
# Example query
my $sql = ‘SELECT * FROM your_table_name’;
my $sth = $dbh->prepare($sql);
$sth->execute();
# Fetch and display results
while (my @row = $sth->fetchrow_array) {
print join(“, “, @row), “\n”;
}
# Clean up
$sth->finish();
$dbh->disconnect();
print “Disconnected from the database.\n”;
Breaking It Down
- Connection String:
The $dsn specifies the ODBC DSN you’ve configured, prefixed with DBI:ODBC:. Replace your_dsn_name with the DSN you set up for your MySQL database. - Connection Attributes:
- RaiseError => 1: Automatically die on errors.
- PrintError => 0: Prevents warnings from being printed automatically.
- AutoCommit => 1: Ensures changes are committed immediately.
- Query Execution:
The script prepares a simple SELECT * query, executes it, and prints the results row by row. - Cleanup:
Always call $sth->finish() and $dbh->disconnect() to release resources properly.
Why Use ODBC?
Using ODBC adds a layer of portability to your applications. If your database backend changes in the future, you can update the DSN and driver without rewriting large portions of your Perl code. This is particularly useful in environments with multiple types of databases or when migrating systems.
Final Thoughts
With just a few lines of Perl code, you can connect to a MySQL database using ODBC and start running queries. While this example demonstrates a basic SELECT, the same connection can be used for inserts, updates, and more complex operations.
Whether you’re maintaining legacy Perl applications or building new scripts to interact with MySQL, ODBC gives you a stable, flexible way to manage database connectivity.


