Saturday, May 26, 2012

Connect Perl to MySQL

If you are a MySQL DBA, one of the most useful things you need to know is Perl. This will make you able to create custom tools such as for example benchmarking tools to run against a MySQL database.

It is extremely easy to use Perl with MySQL - but first you need to install the MySQL Perl module:

ivory:~ user$ perl -MCPAN -e 'install Mysql'

This should be pretty straightforward although sometimes it can complain that it cannot find mysql.h - just make sure to create relevant symbolic links to the path it is looking the include files.

Once you have the Perl module installed you can use the following template script to initiate a connection with MySQL - in this example I am only going to show you how to connect to the database and list all the databases. Follow this blog for other uses and examples.

#!/usr/bin/perl

# PERL MODULE
use Mysql;

# CONFIG VARIABLES
$host = "localhost";
$database = "test";
$user = "testuser";
$pass = "password";

# PERL MYSQL CONNECT
$connect = Mysql->connect($host, $database, $user, $pass);

# LISTDBS()
@databases = $connect->listdbs;
foreach $database (@databases) {
        print "$database\n";
}
Post a Comment