17 June 2011

Getting select query result from DB2 database using perl script

First Install following modules

1. DBI
2. DBD (DB2 Database module)

Use following script to connect to database and fetch the rows from required table.

use strict;
use DBI;

# Open a connection
my $dbh = DBI->connect('dbi:DB2:DATABASE_NAME',
        "DB_USERNAME", "DB_PASSWORD", {RaiseError => 1}) or 

        die "can not connect to database" . $dbh->errstr;

my $stmt = "SELECT * FROM TABLE_NAME";

# Prepare query
my $sth = $dbh->prepare($stmt) or die "Can not prepare statement" . $dbh->errstr;

# Execute Query

my $x = $sth->execute() or  die "Cannot execute: " . $sth->errstr;

# Fetch result
while (my $hash = $sth->selectrow_hashref) {
    print $hash;

selectrow_hashref will contain the columname => value pairs for each row.

No comments:

Post a Comment