Wednesday, September 28, 2011

Write code to connect DB2 and Perl.

#!/usr/bin/perl

use DBI;

#Set Connection String
my $connection_string = "dbi:DB2:DATABASE=$db; HOSTNAME=$hostname; PORT=$port; PROTOCOL=TCPIP; UID=$user; PWD=$pass;";
#Open Connection
my $dbh = DBI->connect($connection_string, $user, $pass) || die "Connection failed for error: $DBI::errstr";
#Set Statement
my $sql = "SELECT * FROM SCHEMA-NAME.TABLE-NAME FETCH FIRST 10 ROWS ONLY";
#Prepare Statement
my $sth = $dbh->prepare($sql) or die "can't prepare: " $dbh->errstr;
#Execute Statement
$sth->execute() or die "can't execute: " $sth->errstr;
#Combine variables with output columns
my ($AppName, $PermValue, $UserName);
$sth->bind_col(1, \$AppName);
$sth->bind_col(2, \$PermValue);
$sth->bind_col(3, \$UserName);
#Iterate through loop to print result set
while ($sth->fetch)
{
        print "$AppName, $PermValue, $UserName\n";
}
$sth->finish();
#Close Connection
$dbh->disconnect();

No comments :