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

Friday, October 9, 2009

Perl: DB Connection details in a seperate file

And finally, moving the connection details into a separate file that you can call from any program.
dbsettings.pl
sub dbinfo() {
 my %mydbinfo = ( db => "cddb",
    host => "localhost",
    user => "myuser",
    passwd => "xxx"
 );
 return %mydbinfo;
}
return true;

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

require "D:\\Documents and Settings\\timj\\perl\\dbsettings.pl" or
die "Can't Open DB Settings File";


my %mydbinfo = dbinfo();
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);

1 comment:

Tim said...

Note:
The die bit of the require command here isn't really working, as the require command dies of it's own accord if it fails to find the file.