Am trying to use database query to print query output to CSV but can't get the output on to separate lines. How to do so?
Here's the code:
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: $!";
This must be a common use case but couldn't find anything about issues with new lines.
()insideqq(), which is rather weird (but seems to work for some reason!), and don't have a semi-colon on the end of the line, which should result in syntax error. You should not ever, for any reason, try to type your source code into a question: Always cut and paste.qq()(and many other perl operators, such asm//,s///,qr//, etc) you can change the parentheses to almost any other punctuation character. This reduces the need to escape characters, such asm/\/usr\/bin\//could bem#/usr/bin/#. But in this case, it seems thatqq()can handle parentheses inside, just so long as they are balanced. I did not know that. One of those edge cases that I am not sure are really useful, but an interesting piece of trivia. :)