使用Perl Text :: CSV从数据库写入

时间:2013-10-13 21:01:06

标签: perl csv

尝试使用数据库查询将查询输出打印到CSV但无法将输出打印到单独的行。怎么做?

以下是代码:

use warnings;
use DBI;
use strict;
use Text::CSV;

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

open my $fh, ">:encoding(utf8)", "new.csv" or die "new.csv: $!";

#set up query
my $dbh = DBI->connect("DBI:mysql:db", "name") or die ("Error:  $DBI::errstr");

my $sql = qq(select * from one_table join two_table using (primary_key));
my $query = $dbh->prepare($sql);
$query->execute;

#loop through returned rows of query and save each row as an array
while ( my (@row ) = $query->fetchrow_array ) {
    #print each row to the csv file
    $csv->print ($fh, [@row]);    
        # every line seems to be appended to same line in "new.csv"
        # tried adding "\n" to no avail 
    }
close $fh or die "new.csv: $!";

这必须是一个常见的用例,但无法找到有关新行问题的任何内容。

3 个答案:

答案 0 :(得分:5)

我认为你的问题是所有的CSV数据都在同一行上?

您应该在CSV对象中设置eol选项:

my $csv = Text::CSV->new ( {
         binary => 1,      # should set binary attribute.
         eol    => $/,     # end of line character
}) or die "Cannot use CSV: ".Text::CSV->error_diag ();

此字符将附加到print中的行尾。您也可以考虑不在每次迭代时从fetchrow调用中复制值,因为print采用数组引用。使用引用会更直接。

while (my $row = $query->fetchrow_arrayref) {
    ....
    $csv->print($fh, $row);

答案 1 :(得分:3)

首先,你在行尾有一个缺少的分号

my $sql = qq(select * from one_table join two_table using (primary_key))

默认情况下,Text::CSV在行尾使用当前值$\输出记录分隔符。而且,默认情况下,它设置为undef,因此您不会打印任何分隔符。

您可以 使用

设置$csv对象
my $csv = Text::CSV->new({ binary => 1, eol => "\n" });

只是显式打印换行符,就像这样。请注意,不需要将行提取到数组中,然后将其复制到匿名数组以使其工作。 fetchrow_arrayref将返回一个数组引用,您可以直接将其传递给print

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

答案 2 :(得分:-1)

试试这个SQL查询

select * from one_table join two_table using (primary_key) 
INTO OUTFILE '/tmp/new.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'