The data table has too many columns to select one by one, so I am trying to pull entire data into a file. There are a number of columns contains datetime for UTC and local time. When I used the following script, all hour information is deleted and only date is saved. How can I easily fix the code to save the entire datetime information?
In summery, all datetime data in csv file was saved as "25-FEB-15" instead of "25-FEB-15 HH:MM:SS AM -08:00"
open(OUTFILE, "> ./outputfile.csv");
my($dbh,$sth);
$dbh = DBI->connect("xxx")
my $sqlGetEid = "
select *
from Table_1
where MARKET = 'Chicago' and DATETIMELOCAL >= '22-FEB-2015' and DATETIMELOCAL < '01-MAR-2015'
";
my $curSqlEid = $dbh->prepare($sqlGetEid);
$curSqlEid->execute();
my $counter = 0;
my $delimiter = ',';
my $fields = join(',', @{ $curSqlEid->{NAME_lc} });
print "$fields\n";
printf OUTFILE "$fields\n";
while (my @row = $curSqlEid->fetchrow_array) {
my $csv = join(',', @row)."\n";
printf OUTFILE "$csv";
$counter ++;
if($counter % 10000 == 0){
print $csv, "\n";
}
}
I have fixed codes according to the comments below, but the problem is not resolved yet. The DB I am using is Oracle, so MySQL based codes seems not compatible. The problem is narrow down to the datetime formats that Oracle uses, so by properly handling the format this problem can be resolved. But I am not sure which perl package I have to use to nicely handle Oracle datatime formats.
use DBI;
use DBD::Oracle qw(:ora_types);
use Compress::Zlib;
use FileHandle;
use strict;
use warnings;
use DateTime;
use Data::Dumper;
use Text::CSV_XS;
use DateTime::Format::DateParse;
use DateTime::Format::DBI;
open(OUTFILE, "> ./output.csv");
my $dbh = DBI->connect("xxx")
my $sth = $dbh->prepare("SELECT * FROM Table_1");
$sth->execute;
my $fields = join(',', @{ $sth->{NAME_lc} });
#EXTRACT COLUMN NAMES
my @col_names = @{ $sth->{NAME_lc} } ;
my $column_names = join ", ", @col_names;
my $select = "
select $column_names
from Table_1
where MARKET = 'Chicago' and DATETIMELOCAL >= '22-FEB-2015' and DATETIMELOCAL < '01-MAR-2015'
";
my $query = $dbh->prepare($select);
$query->execute;
#WRITE DATA TO CSV FILE
my $csv_attributes = {
binary => 1, #recommneded
eol => $/, #recommended(I wonder why it's not $\ ?)
};
my $csv = Text::CSV_XS->new($csv_attributes);
my $fname = 'data.csv';
open my $OUTFILE, ">", $fname
or die "Couldn't open $fname: $!";
$csv->print($OUTFILE, \@col_names);
$csv->column_names(@col_names); #Needed for print_hr() below
while (my $row = $query->fetchrow_arrayref) {
print $row->[0];# $row->{datetimelocal} does not work
my $datetime = DateTime::Format::DBI->parse_datetime( $row->[0]) ; # This might be wrong
$row->[0] = strftime("%d-%b-%y %I:%M:%S %p", $datetime);
$csv->print($OUTFILE, $row);
}
close $OUTFILE;
$query->finish;
$dbh->disconnect;