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

前端之家收集整理的这篇文章主要介绍了使用Perl Text :: 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: $!";

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

解决方法

我认为你的问题是你的所有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 ();

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

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

猜你在找的Perl相关文章