Perl DBI Template for Oracle |
This is a standard template that I start with when creating a Perl script that connects to an Oracle database.
It has the advantage of having command line arguments in place via the Getopt::Long module, a database connection via the DBI module, a sample query also via DBI, as well as some standard settings that I like to include in my Perl/Oracle scripts.
# !/usr/bin/perl -w # template for DBI programs
use warnings; use DBI; use strict; use Getopt::Long; my %optctl = ();
Getopt::Long::GetOptions( \%optctl, "database=s", "username=s", "password=s", "sysdba!", "sysoper!", "z","h","help");
my($db, $username, $password, $connectionMode); $connectionMode = 0; if ( $optctl{sysoper} ) { $connectionMode = 4 } if ( $optctl{sysdba} ) { $connectionMode = 2 } if ( ! defined($optctl{database}) ) { Usage(); die "database required\n"; } $db=$optctl{database}; if ( ! defined($optctl{username}) ) { Usage(); die "username required\n"; } $username=$optctl{username}; $password = $optctl{password};
# print "USERNAME: $username\n"; #print "DATABASE: $db\n"; #print "PASSWORD: $password\n"; #exit;
my $dbh = DBI->connect( 'dbi:Oracle:' . $db, $username, $password, { RaiseError => 1, AutoCommit => 0, orasessionmode => $connectionMode } );
die "Connect to $db failed \n" unless $dbh; $dbh->{RowCacheSize} = 100; my $sql=q{select from dual};
my $sth = $dbh->prepare($sql,{orachecksql => 0 }); $sth->execute; while( my $ary = $sth->fetchrowarrayref ) { print "\t\t$${ary[0]}\n"; }
$sth->finish; $dbh->disconnect;
sub Usage { print "\n"; print "usage: DBItemplate.pl\n"; print " DBItemplate.pl -database dv07 -username scott -password tiger [-sysdba || -sysoper]\n"; print "\n"; }