3

The code below works, but all of the data displays in one row(but different columns) when opened in Excel. The query SHOULD display the data headings, row 1, and row 2. Also, when I open the file, I get a warning that says "The file you are trying to open,'xxxx.csv', is in a different format than specified by the file extension. Verify that the file is not corrupted...etc. Do you want to open the file now?" Anyway to fix that? That may be the cause too.

tldr; export to csv with multiple rows - not just one. fix Excel error. Thanks!

#!/usr/bin/perl
use warnings;
use DBI;
use Text::CSV;


# local time variables
($sec,$min,$hr,$mday,$mon,$year) = localtime(time);
$mon++;
$year += 1900;

# set name of database to connect to
$database=MDLSDB1;

# connection to the database
my $dbh = DBI->connect("dbi:Oracle:$database", "", "")
or die "Can't make database connect: $DBI::errstr\n";

# some settings that you usually want for oracle 10 
$dbh->{LongReadLen} = 65535; 
$dbh->{PrintError} = 0;  

# sql statement to run
$sql="select * from eg.well where rownum < 3";

my $sth = $dbh->prepare($sql);
$sth->execute();


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

open my $fh, ">:raw", "results-$year-$mon-$mday-$hr.$min.$sec.csv"; 

$csv->print($fh, $sth->{NAME});

while(my $row = $sth->fetchrow_arrayref){      

$csv->print($fh, $row);
}

close $fh or die "Failed to write CSV: $!"; 
4
  • 2
    Well, first off, you're trying to print an array reference to a file handle...that'll result in lines like ARRAY(0x323523), etc. Don't trust Excel. Don't be afraid to actually look at the contents of a csv file (via cat, vi, etc).
    – user554546
    Jun 1, 2012 at 20:36
  • Also, you have absolutely no error checking, so you have no way of telling whether you've successfully connected to the database, whether the table eg.well exists, whether the query was successfully completed, whether zero rows were returned, etc.
    – user554546
    Jun 1, 2012 at 20:39
  • And furthermore, unless you're coding a throw-away one-liner, you should use strict.
    – user554546
    Jun 1, 2012 at 20:42
  • Ok i'll be sure to do that. In my defense I started learning perl yesterday and have used google to help haha Jun 1, 2012 at 21:39

2 Answers 2

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

CSV rows are delimited by newlines. Just simply add a newline after each row.

2
  • 2
    I get next error: Expected fields to be an array ref at ... for $csv->print($fh, "\n"); May 5, 2016 at 13:51
  • 2
    @EugenKonkov: That line should have been print $fh "\n"; because the $csv object is expecting an array that holds the row to be printed. I submitted an edit, but it needs to be reviewed. Jun 13, 2016 at 16:52
2

I think another solution is to use the instantiation of the Text::CSV object and pass along the desired line termination there...

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

becomes:

my $csv = Text::CSV->new({ binary => 1, eol => "\r\n" })
  or die "Cannot use CSV: " . Text::CSV->error_diag();
1
  • This is the correct solution. The query for exporting to CSV mysql includes defining how a line is terminated with \r\n. If you don't include "eol => "\r\n" after setting the binary flag, when you export, you'll find that the first row of data is merged into a single row with the header. You'll also need to remove the print $fh "\n" line as well, or you'll have a blank row between each row of data.
    – TechDex
    Jan 4, 2021 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.