Reputation: 1
Hey Im coding a perl script which needs to get data from a database. But when I get a return value its comes back in an array so i dereference it. Yet it still prints out nothing. I ran the command in sqlplus and it worked there without issue. Im not sure how to solve this
Code:
my $sth = $dbh->prepare("select XMLRECORD from F_COMPANY") or
die "Couldnt prepare statement: " . $dbh->errstr;
$sth->execute();
# loop through the returned data
while( my ($row) = $sth->fetchrow_array()){
print "@$row\n";
}
OUTPUT: Literally nothing
Upvotes: 0
Views: 827
Reputation: 385847
ALWAYS use use strict; use warnings;
. It would have caught your error.
fetchrow_array
does NOT return an array reference. It returns the values of the row as individual scalars.
You want
while ( my $row = $sth->fetchrow_arrayref() ) { # aka `->fetch`
say "@$row";
}
or
while ( my @row = $sth->fetchrow_array() ) {
say "@row";
}
use strict;
use warnings;
use feature qw( say );
use DBI;
my $dbh = DBI->connect(
"dbi:SQLite:dbname=:memory:",
"", "",
{
AutoCommit => 1,
RaiseError => 1,
PrintError => 0,
PrintWarn => 1,
}
);
$dbh->do( "CREATE TEMPORARY TABLE `Table` ( `a` INT, `b` INT )" );
$dbh->do( "INSERT INTO `Table` VALUES ( 123, 456 )" );
{
my $sth = $dbh->prepare( "SELECT * FROM `Table`" );
$sth->execute();
while ( my $row = $sth->fetchrow_arrayref() ) { # aka `->fetch`
say "@$row";
}
}
{
my $sth = $dbh->prepare( "SELECT * FROM `Table`" );
$sth->execute();
while ( my @row = $sth->fetchrow_array() ) {
say "@row";
}
}
Output:
123 456
123 456
Upvotes: 5