我正在尝试使用数据库查询将查询输出打印到 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: $!";
这一定是一个常见的用例,但找不到任何关于新行问题的信息。