Just somewhere to keep my notes while I'm playing.

Wednesday, July 22, 2009

A Perl Script that accesses MySQL

Last year I posted a simple Perl script that accesses a PostgreSQL database using the DBI connector. I decided that I should do the same for MySQL. I'm using Active State Perl on Windows XP. Amusingly, this version does not include the MySQL connectors as default, but it's easy enough to add using perl ppm (Perl's Perl Package Manager).

I want a simple script that lists out artists and their CDs in my database.


#!/usr/bin/perl
use strict;
use DBI();
my $dbh1 = DBI->connect("DBI:mysql:database=cddb;host=localhost","uuuu", "xxxxxx", { raiseError => 1, AutoCommit => 0 })
|| die "Database connection not made: $DBI::errstr";
my $sql = "SELECT artist.name, cd.title FROM artist, cdtable AS cd WHERE artist.id = cd.artid";
my $sth = $dbh1->prepare($sql);

$sth->execute();

my( $name, $title );
$sth->bind_columns( \$name, \$title );

print "Name\t\tTitle\n";
while( $sth->fetch() ) {
print "$name\t$title\n";
}
$dbh1->disconnect() if($dbh1)

D:\Documents and Settings\timj\perl>c:\Perl\bin\perl cd.pl
Name Title
Phatfish Guaranteed
Phatfish 15
Bethany Dillon Waking Up
Bethany Dillon Bethany Dillon
Bethany Dillon Imagination
Nick Drake Made To Love Magic
Nick Drake Five Leaves Left
Nick Drake Bryter Layter

D:\Documents and Settings\timj\perl>


That's about as simple as it get, I'm sure that there is far more to it than that, but this will do for now!
Tim

No comments: