Basic MySql Connect and Select in Perl

Here is an example of connecting to a mysql database and issuing a simple SELECT statement that returns more than one row. Make sure you have the Perl DBI package istalled on your system (you will get an error when you try o run the code if you don’t).


#!/usr/bin/perl
use DBI;
$|=1;

# change mydatabase to your database name
# change username to your mysql username
# change password to your mysql password
$dsn = "DBI:mysql:mydatabase;localhost";
$dbh = DBI->connect($dsn, 'username', 'password');

if ( !defined $dbh ) {
exit;
}

# use the four lines below if the query results
# in many rows or if you get 'out of memory' errors

$SQL_QUERY=<prepare( "$SQL_QUERY" );
$cursor->execute;

while ( @row = $cursor->fetchrow ) {
print "@row\n";
}
$cursor->finish;
$dbh->disconnect;

If you need to install DBI, you can do it easily by running the following command from any shell as root :

perl -MCPAN -e ‘install Bundle::DBI’

Documentation on the DBI module is available at CPAN :

http://search.cpan.org/~timb/DBI/


About this entry