title: Perl script to export sql query to csv
body: <p>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.</p>
  
  <p>tldr; export to csv with multiple rows - not just one. fix Excel error. Thanks!</p>
  
  <pre><code>#!/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-&gt;connect("dbi:Oracle:$database", "", "")
  or die "Can't make database connect: $DBI::errstr\n";
  
  # some settings that you usually want for oracle 10 
  $dbh-&gt;{LongReadLen} = 65535; 
  $dbh-&gt;{PrintError} = 0;  
  
  # sql statement to run
  $sql="select * from eg.well where rownum &lt; 3";
  
  my $sth = $dbh-&gt;prepare($sql);
  $sth-&gt;execute();
  
  
  my $csv = Text::CSV-&gt;new ( { binary =&gt; 1 } )             
  or die "Cannot use CSV: ".Text::CSV-&gt;error_diag (); 
  
  open my $fh, "&gt;:raw", "results-$year-$mon-$mday-$hr.$min.$sec.csv"; 
  
  $csv-&gt;print($fh, $sth-&gt;{NAME});
  
  while(my $row = $sth-&gt;fetchrow_arrayref){      
  
  $csv-&gt;print($fh, $row);
  }
  
  close $fh or die "Failed to write CSV: $!"; 
  </code></pre>