Perl DBI Template for Oracle |
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,
ora_session_mode => $connectionMode
}
);
die "Connect to $db failed \n" unless $dbh;
$dbh->{RowCacheSize} = 100;
my $sql=q{select * from dual};
my $sth = $dbh->prepare($sql,{ora_check_sql => 0 });
$sth->execute;
while( my $ary = $sth->fetchrow_arrayref ) {
print "\t\t$${ary[0]}\n";
}
$sth->finish;
$dbh->disconnect;
sub Usage {
print "\n";
print "usage: DBI_template.pl\n";
print " DBI_template.pl -database dv07 -username scott -password tiger [-sysdba || -sysoper]\n";
print "\n";
}