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

Monday, October 12, 2009

Perl: DB Connection details on the command line

What if you want to connect to a database, passing your parameters in on a command line? Here's a handy routine to do that:

First the included code

sub dbinfo() {
 my %mydbinfo = ( db => "",
    host => "",
    user => "",
    passwd => ""
 );


 die "Not Enough Parameters" unless ($#ARGV > 5);

 for (my $i=0; $i <= $#ARGV; $i++) {
  $mydbinfo{db} = $ARGV[++$i] if ( $ARGV[$i] eq "-d" ) ;
  $mydbinfo{host} = $ARGV[++$i] if ( $ARGV[$i] eq "-h" ) ;
  $mydbinfo{user} = $ARGV[++$i] if ( $ARGV[$i] eq "-u" ) ;
  $mydbinfo{passwd} = $ARGV[++$i] if ( $ARGV[$i] eq "-p" ) ;
 
 }
 return %mydbinfo;
}
return true;


Next the code that calls this routine

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

require "D:\\Documents and Settings\\timj\\perl\\commanddbsettings.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)

and here it is in action

D:\Documents and Settings\timj\perl>testcommandline.pl -d cddb -h localhost -u myuser -p xxx
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>

It's not perfect, it doesn't do a lot of validation, and it doesn't allow you to enter the password with "echo off", but it's a good starting point.

No comments: