简体   繁体   中英

Fetch all rows of a ORACLE SQL query using PERL Script

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";
}

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM