Perl and MySQL using DBI

Published March 06, 2010

This is a sample Perl script to select data from MySQL table using DBI module.

This tutorial shows how to use Perl to retrieve rows from a MySQL table using Perl DBI.

You require these:

  • Perl DBD::MySQL module
  • MySQL server

If you haven't got DBD::MySQL installed, you can install it with this:

sudo perl -MCPAN -e "install DBD::MySQL"

Then, test if DBD::MySQL is correctly installed with this:

perl -MDBD::MySQL -e "print 1234"

If it prints 1234, you know it is installed.

Table of Contents

Create table "domains"

Create this table by running this SQL command in MySQL:

CREATE TABLE IF NOT EXISTS `domains` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `url` varchar(100) NOT NULL,
  `descr` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ;

Let's populate this table by executing this INSERT command in MySQL. This will insert 50 rows of domain names, URLs and descriptions.