Friday, June 5, 2009

Perl DBI interface to MySQL

The DBI module can be used to work with databases like Oracle, MySQL, and Informix in Perl. Following is an example to query names and phone numbers in the Info table of Supplier database with MySQL database.

#!/usr/bin/perl

use DBI;
use strict;

my $driver = "mysql";
my $database = "Supplier";
my $source = "DBI:$driver:database=$database";
my $userid = "XXX";
my $password = "XXX";
my $dbh = DBI->connect($source, $userid, $password )
or die $DBI::errstr;

my $sth = $dbh->prepare("SELECT Name, Phone FROM Info");
$sth->execute() or die $DBI::errstr;
print "Company, Phone:\n";
while (my @row = $sth->fetchrow_array()) {
my ($name, $phone ) = @row;
print "$name, $phone\n";
}
$sth->finish();

No comments: