我正在尝试从Perl脚本连接到Oracle DB并从中获取输出。我写了下面的代码
#!/usr/local/bin/perl
use DBI;
use warnings;
use strict;
sub retrieve_data {
my ( $dbh, $rwnum ) = @_;
my @row;
my $selstmt = $dbh->prepare("select * from DIT_NOFUTURE_TMP1 where rownum < 5")
or die "Can't prepare SQL statement: ", $dbh->errstr(), "\n";
$selstmt->execute($rwnum);
while ( @row = $selstmt->fetchrow_array ) { # retrieve one row
print join( ", ", @row ), "\n";
}
}
my $dsn = "dbi:Oracle:DBInstance";
my $dbh = DBI->connect( $dsn, 'username', 'password', { AutoCommit => 0 } );
my $rno = 5;
unless ($dbh) {
print "\nError : DBI connect failed: DBI:errstr\n";
print "Error : Unable to connect to database $dsn\n";
exit(-1);
}
retrieve_data $dbh , $rno;
exit(0);
预期产出:
SQL> select * from DIT_NOFUTURE_TMP1 where rownum < 5;
ORDER_ID ORDER_UNIT CUSTOMER_ID
---------- ---------- --------------
2534 2535 100000046
2560 2561 100000109
2523 2524 100000045
2525 2526 100000045
收到的输出:
DBD::Oracle::st execute failed: called with 1 bind variables when 0 are needed [for Statement "select * from DIT_NOFUTURE_TMP1 where rownum<5"] at dbcon.pl line 13.
DBD::Oracle::st fetchrow_array failed: ERROR no statement executing (perhaps you need to call execute first) [for Statement "select * from DIT_NOFUTURE_TMP1 where rownum<5"] at dbcon.pl line 14.
Issuing rollback() due to DESTROY without explicit disconnect() of DBD::Oracle::db handle (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=135.208.32.97)(PORT= 1521))(CONNECT_DATA =(SERVER=DEDICATED)(SERVICE_NAME=PRDMOMS))) at dbcon.pl line 36.
请为此提出一些解决方案。
答案 0 :(得分:5)
如错误所示,您的语句句柄并不期望任何参数(因为查询中没有占位符)。
如果数字5应该被参数替换,只需将查询更改为
my $selstmt = $dbh->prepare('select * from DIT_NOFUTURE_TMP1 where rownum < ?')
or die "Can't prepare SQL statement: ", $dbh->errstr(), "\n";
否则,删除参数:
$selstmt->execute;