You could save column headings a couple of ways. The easiest is to simply define the column headings in an array and then print them out with a join. If the headings vary, you can usually pull the column headings from the db connection. The following example works for ODBC but I believe that DBI has a similar option. I cobbled this snippet from programs that I have in production so I've skipped the setup, initialization and most of the error checking that should accompany the code.
my ($rtncd, $db) = OpenODBC($cfg{obtsdsn}, $cfg{dbf01});
my $colnames = '';
my $outfile = 'testfile.csv';
my $sqlstmt = '';
my @rowdata = ();
open(OUTFILE, ">$outfile") ||
die "Could not open output file $outfile\n$!\n";
$colnames = join(',',@{GetColNames($db,$tblname)});
print OUTFILE $colnames."\n";
$sqlstmt = qq|SELECT TOP 10 * FROM $tblname|;
if($db->Sql("$sqlstmt")){
$rtncd = -1;
print "error!!Could not query table ".
"$tblname\n$sqlstmt\n".$db->Error();
}else{
while($db->FetchRow()){
# retrieve and initialize data
@rowdata = map{ $_ ||= '' } $db->Data();
# doesn't account for comma in data
print OUTFILE join(',',@rowdata);
print OUTFILE "\n"; # one per line
}
}
close(OUTFILE);
$db->Close;
exit;
} #end main()
############################################################;
sub GetColNames{
my $db = shift;
my $tblname = shift;
my $rtncd = 0;
my $sqlstmt = qq|SELECT TOP 1 * FROM $tblname|;
my @colnames = ();
if($db->Sql("$sqlstmt")){
$rtncd = -1;
print "error!![0105]Could not query table ".
"$tblname\n$sqlstmt\n".$db->Error();
}else{
if($db->FetchRow()){
push @colnames, $db->{fnames}[$_]
for (0..$#{$db->{fnames}});
}
}
return \@colnames;
} #end GetColNames()
############################################################;
|