0

如何将 Oracle SQL 查询结果重定向到驱动器上的外部 CSV 文件,同时在 perl 中将它们打印到屏幕上

这是我打算做的

my $dbh =  DBI->connect('dbi:ODBC:Test2', 'XXX', 'XXXX') || die ("Connection Failed      \n");
$sql="select a,b from xxx";
my $sth = $dbh->prepare($sql);
$sth->execute();
my $dat;

while( $dat = $sth->fetchrow_hashref() ){ print ("$dat->{a}",print ("$dat->{b}" *这里我在屏幕上看到结果 }

**My main challenge is to get the results into a csv file on my local disk -- Any   help    would be appreciated.....**
4

1 回答 1

1

我会使用 CPAN 模块Text::CSV。该模块将处理所有 CSV 特定处理(例如引用)。

use Text::CSV;

my $csv = Text::CSV->new ( { binary => 1 } )  # should set binary attribute.
             or die "Cannot use CSV: ".Text::CSV->error_diag ();
open $fh, ">:encoding(utf8)", "my.csv";

. . .

while( $dat = $sth->fetchrow_hashref() ){ 
    print "$dat->{a} $dat->{b}\n";
    $csv->print ($fh, [ $dat->{a}, $dat->{b} ]);
}

. . .

close $fh or die "Failed to write CSV: $!";
于 2012-05-23T14:49:16.867 回答