如何仅在SQL查询返回超过0行时写入文件-Perl
我有这段代码,只有当SQL查询返回的行数超过0行时,我才希望打开该文件(Output.csv)。我尝试使用mysqli_num_rows()但没有帮助。这是我目前的代码:如何仅在SQL查询返回超过0行时写入文件-Perl,sql,perl,Sql,Perl,我有这段代码,只有当SQL查询返回的行数超过0行时,我才希望打开该文件(Output.csv)。我尝试使用mysqli_num_rows()但没有帮助。这是我目前的代码: #!/usr/bin/perl -w BEGIN { $ENV{ORACLE_HOME}='/u01/app/oracle/product/11.1.0/'; } use strict; use DBI; use utf8; #use Text::CSV; my $DB='database'; my $db_use
#!/usr/bin/perl -w
BEGIN {
$ENV{ORACLE_HOME}='/u01/app/oracle/product/11.1.0/';
}
use strict;
use DBI;
use utf8;
#use Text::CSV;
my $DB='database';
my $db_user='user';
my $password=`/usr/bin/pmo view password -u $db_user -t $DB`; chomp($password); my $db = DBI->connect( "dbi:Oracle:database", $db_user, $password )
|| die( $DBI::errstr . "\n" );
$db->{AutoCommit} = 0;
$db->{RaiseError} = 1;
$db->{ora_check_sql} = 0;
$db->{RowCacheSize} = 16;
my $sth = $db->prepare("SELECT * from my table T where T.last_updates=(SYSTDATE -2) ");
open my $fh, '>>', 'Output.csv' or die "Could not open file Output.csv: $!";
$sth->execute;
while (my @res = $sth->fetchrow_array) {
print $fh qq{$res[0]\t$res[1]\n};
}
close $fh;
print "If you see this, execute phase succeeded without a problem.\n";
END {
$db->disconnect if defined($db);
}
好的,当你遇到第一行时打开文件
my $fh; # = undef
while (my @res = $sth->fetchrow_array) {
unless ($fh) {
open $fh, '>>', 'Output.csv' or die "Can't open output file: $!";
}
print $fh qq{$res[0]\t$res[1]\n};
}
close $fh if $fh;
使用函数来确定结果集中存在多少行通常是个坏主意。它可能非常昂贵。因为您无论如何都要读取所有返回的行,所以没有意义。(如果您只需要计数,
选择计数(*)…
,这样数据库就只需要计数,而您不会将一个大的结果集从数据库带到应用程序中,只为了丢弃它的内容。)mysqli_num_rows()?如果这有帮助,那将是非常令人惊讶的,因为这是一个PHP函数。我的意思是,我正在搜索一个函数,该函数在Pleaseuse warnings
的可能副本中执行相同的任务,而不是它所帮助的anks Mat上的-w
命令行选项:)请,永远不要尝试自己编写CSV文件-有太多的陷阱。可以使用Text::CSV,也可以使用DBI,DBD::CSV,因为使用数据库。