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

Wednesday, October 7, 2009

Perl: Storing your DB Connect in a hash

This is a half-way house script, that uses a hash to store the database information for the connect.

#!/usr/bin/perl
use strict;
use DBI();

my %mydbinfo = ( db => "cddb",
host => "localhost",
user => "myuser",
passwd => "xxx"
);

my $dbconnect = "DBI:mysql:database=" . $mydbinfo{db} . ";host=" . $mydbinfo{host} ;

my $dbh1 = DBI->connect($dbconnect,$mydbinfo{user}, $mydbinfo{passwd}, { 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);



This has the advantage of putting all the details neatly at the start of the code, but still has the full DB connect details hard coded, which is obviously something to avoid in most circumstances.

No comments: