用于将sql查询导出到csv的Perl脚本

时间:2012-06-01 20:29:55

标签: sql perl oracle csv

以下代码有效,但在Excel中打开时,所有数据都显示在一行(但不同的列)中。查询应该显示数据标题,第1行和第2行。另外,当我打开文件时,我收到一条警告:“你要打开的文件'xxxx.csv'的格式与由文件扩展名指定。验证文件是否已损坏...等。您要立即打开该文件吗?“无论如何要解决这个问题?这也可能是原因。

tldr;导出到多行的csv - 而不仅仅是一行。修复Excel错误。谢谢!

#!/usr/bin/perl
use warnings;
use DBI;
use Text::CSV;


# local time variables
($sec,$min,$hr,$mday,$mon,$year) = localtime(time);
$mon++;
$year += 1900;

# set name of database to connect to
$database=MDLSDB1;

# connection to the database
my $dbh = DBI->connect("dbi:Oracle:$database", "", "")
or die "Can't make database connect: $DBI::errstr\n";

# some settings that you usually want for oracle 10 
$dbh->{LongReadLen} = 65535; 
$dbh->{PrintError} = 0;  

# sql statement to run
$sql="select * from eg.well where rownum < 3";

my $sth = $dbh->prepare($sql);
$sth->execute();


my $csv = Text::CSV->new ( { binary => 1 } )             
or die "Cannot use CSV: ".Text::CSV->error_diag (); 

open my $fh, ">:raw", "results-$year-$mon-$mday-$hr.$min.$sec.csv"; 

$csv->print($fh, $sth->{NAME});

while(my $row = $sth->fetchrow_arrayref){      

$csv->print($fh, $row);
}

close $fh or die "Failed to write CSV: $!"; 

2 个答案:

答案 0 :(得分:10)

while(my $row = $sth->fetchrow_arrayref){   
  $csv->print($fh, $row);
  $csv->print($fh, "\n");
}

CSV行由换行符分隔。只需在每行后添加换行符即可。

答案 1 :(得分:0)

我认为另一个解决方案是使用Text::CSV对象的实例化并在那里传递所需的行终止...

my $csv = Text::CSV->new ( { binary => 1 } )             
  or die "Cannot use CSV: " . Text::CSV->error_diag();

变为:

my $csv = Text::CSV->new({ binary => 1, eol => "\r\n" })
  or die "Cannot use CSV: " . Text::CSV->error_diag();