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

标签 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: $!";

这一定是一个常见的用例,但找不到任何关于换行的问题。

最佳答案

我假设您的问题是所有 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);

关于perl - 使用 Perl Text::CSV 从数据库写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19350231/

相关文章:

perl - 为什么这会返回空字符串?

php - 可以在 Perl 文件中包含 PHP 吗?

perl - 获取通过 $self->send() 在 Perl Expect 模块中的远程主机上执行的命令的输出

Javascript,删除/忽略 CSV 文件的最后一行

Perl 除法程序

regex - 为什么我的 ack 正则表达式会得到额外的、意想不到的结果?

python - 从 csv/2d 数组中提取一系列元素

php - 使用 phpMyAdmin 将使用长数字的电子表格导入 MySQL 的最佳方法

csv - 将CSV加载到Redshift : "Missing newline: Unexpected character found at location 2"

python - 将单列 .csv 文件转换为列表变量