Fetching results in Perl
The Perl DBI module provides methods for connecting to a database, preparing and issuing SQL statements, and fetching rows from result sets.
About this task
This procedure fetches results from an SQL query.
Restrictions
Because the Perl DBI module supports only dynamic SQL, you cannot use host variables in your Perl Db2® applications.
Procedure
To fetch results:
Examples
The example shows how to connect to a database and issue a SELECT statement from an application written in Perl.
#!/usr/bin/perl
use DBI;
my $database='dbi:DB2:sample';
my $user='';
my $password='';
my $dbh = DBI->connect($database, $user, $password)
or die "Can't connect to $database: $DBI::errstr";
my $sth = $dbh->prepare(
q{ SELECT firstnme, lastname
FROM employee }
)
or die "Can't prepare statement: $DBI::errstr";
my $rc = $sth->execute
or die "Can't execute statement: $DBI::errstr";
print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n";
print "$sth->{NAME}->[0]: $sth->{NAME}->[1]\n";
while (($firstnme, $lastname) = $sth->fetchrow()) {
print "$firstnme: $lastname\n";
}
# check for problems that might have terminated the fetch early
warn $DBI::errstr if $DBI::err;
$sth->finish;
$dbh->disconnect;