如何使用perl在csv文件中保存所选数据

时间:2014-03-01 07:14:13

标签: oracle perl csv

Mine Perl脚本

my$sth = $dbh->prepare("SELECT city,state address FROM address ");
$sth->execute;
    DBI::dump_results($sth);

以上脚本运行正常,输出效果正好如下

'aaa', 'aa'
'aaa', 'aa'
'city', 'KA'
'city', 'KA'
'city', 'KA'

我的问题是结果输出应保存在我本地计算机的.csv文件中。是否有可能达到我的要求,请让我知道

3 个答案:

答案 0 :(得分:1)

试试这个:

my $csv = Text::CSV->new ( { eol => "\n" } );
my $sql = "SELECT city,state address FROM address";

my $rows = $dbh->selectall_arrayref($sql);


open $fh, ">", "new.csv" or die "new.csv: $!";
for my $row (@$rows) {
  $csv->print ($fh, $row);
}
close $fh or die "new.csv: $!";

答案 1 :(得分:1)

从$ sth获取并使用Text::CSV_XSText::CSV生成CSV数据:

my $select = $db->prepare('select city, state address from address');
$select->execute;

my $c = 'Text::CSV'->new({ eol => "\n" });
open my $OUT, '>', 'new.csv' or die $!;
while (my $row = $select->fetchrow_arrayref) {
    $c->print($OUT, $row);
}
close $OUT or die $!;

答案 2 :(得分:0)

这就是您需要的所有测试代码。

my $csv = Text::CSV->new( { eol => "\n" } );

open my $fh, ">", "data.csv" or die $!;

foreach my $row ( @{ $dbh->selectall_arrayref("SELECT city,state address FROM address") } ) {
    $csv->print( $fh, $row );
}

close $fh;