A library of database functions, using just DBI
########################################################################### # # Name dbfunctions.pm # Description : # Perl library for database functions # ###########################################################################sub dbFunctions { print "Functions in dbfunctions.pmn"; print "====================n"; print "openDBn"; print " Open the mysql database.n"; print "doDBI (<SQL>) n"; print " Execute <SQL> on database opened on dbhn"; print " Returns the result as stringn"; print "doCursor (dbh, <SQL>) n"; print " Execute <SQL> on database opened on dbhn"; print " Returns the result as an array (foreach on it returns strings)n"; print "doCursorAoA (<SQL>) n"; print " Execute <SQL> on database opened on dbhn"; print " Returns an array of array references (foreach on it returns arrays)n"; }# open de database. Returns the handler where the database is openend on. # call like $DBH = &opendb() sub openDB { my $serverName = "localhost"; my $serverPort = "3306"; my $serverUser = "theuser"; my $serverPass = "thepassword"; my $serverDb = "thedatabase"; my $dbh = DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort;user=$serverUser;password=$serverPass"); return ($dbh); }# Just executing some SQL, returns the result as string # call like $result = &doDBI($DBH,'SQL statement') sub doDBI { my ($dbh,$SQL) = @_; my $rv = $dbh->do($SQL); return ($rv) }# For select statement that return a single field from multiple rows # call like @result = &doCursor($DBH,'SQL statement') sub doCursor { my ($dbh,$SQL) = @_; my @Return = (); my @Field = (); my $cursor; # print "$SQL n"; $cursor = $dbh->prepare($SQL); $cursor->execute(); while ( @Field = $cursor->fetchrow ) { push(@Return,@Field); } $cursor->finish; return (@Return) } # For select statement that return a multiple fields from multiple rows # call like: # @result = &doCursor($DBH,'SQL statement') # foreach $dummy (@result) { # ($field1,$field2,$field3) = @dummy; # } sub doCursorAoA { my ($dbh,$SQL) = @_; my @Return = (); my @Field = (); my $cursor; $cursor = $dbh->prepare($SQL); $cursor->execute(); while ( @Field = $cursor->fetchrow ) { push @Return, [ @Field ]; } $cursor->finish; return (@Return) }1;