0

I need to fetch all rows from an oracle sql query and then loop through each rows using PERL.

Below is some sample data and table

create table t1 (col1 varchar2(30));

insert into t1 values ('row1');
insert into t1 values ('row2');
insert into t1 values ('row3');
insert into t1 values ('row4');
insert into t1 values ('row5');

commit;

i have written PERL script like below to fetch above table --

# connexion a la base
my $dbh = DBI->connect( 'dbi:Oracle:'.$dbname,
    $dbusername,
    $pass,
    {   PrintError => 0,
        RaiseError => 1
    }   
) || die "Erreur lors de la connexion: $DBI::errstr";

print ("Connexion à la base de données $dbname avec $dbusername OK \n");

$requete = "select col1 from t1";

$sth_sql = $dbh->prepare($requete);
$sth_sql->execute(@row);
@row=$sth_sql->fetchrow_array;

my $size = @row;

print $size;

#$first=@row[0];
#$sec=@row[1];

print $sec;

print $first;

foreach $script_name (@row) {
  print "$script_name\n";
}

the above code is returning only one row and size of the array is showing only 1 element in it.

I need to fetch all fives rows and then loop through them one by one.

please suggest what i am missing here !!

I am using oracle database.

Thanks

EDIT :

I have made some changes and it is working fine now

$requete = "select col1 from t1";

$sth_sql = $dbh->prepare($requete);
$sth_sql->execute();
#@row=$sth_sql->fetchrow_array;
$sth_sql->bind_columns(undef, \$script_name);


print $sec;

print $first;

while ($sth_sql->fetch()) {
  $script_sql=$script_name.".sql";
  print "$script_sql\n";
}

1 Answer 1

2

The ->fetchrow_array function is documented in DBI. There you'll see documented that you can either use it within a loop:

$sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");

$sth->execute( $baz );

while ( @row = $sth->fetchrow_array ) {
  print "@row\n";
}

to retrieve all rows sequentially, or that you can use the ->fetchall_arrayref method to retrieve the complete resultset in one go:

$sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");

$sth->execute( $baz );

my $rows = $sth->fetchall_arrayref;

for my $row (@$rows) {
  print "@row\n";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply Corion. I have made some other changes after going through lots of documentations. Posted in Question EDIT section.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.