in reply to Multiple queries on DBI corresponding to multiple csv files?
Some untested code follows...
I would use {RaiseError => 1} in the DBI connect. That way you do not have to check with "or die" for every prepare or whatever. A "die" will happen automatically.
The big problem here is that writing a CSV file can be devilishly tricky when there are imbedded "," in the data field! Like 'James,Bob,Jr' or whatever. I think (if I remember right) that also a string should be in quotes if there are embedded spaces, "Jessie Jones". The full CSV spec is more complicated than you might think. There are also "bad" implementations that don't meet the spec. The Perl CSV module pretty much "comes up with the ball", even for not quite right input. Generating a proper CSV output is easier than reading a "supposed CSV" input, however there is more than one way to screw this up.
Mileage varies, but often I use the pipe "|" character instead of a comma "," for writing a simple CSV file. That way I don't have to worry about using the CSV module. I only do that for files which I privately consume - not for export to other programs. However, I actually receive multi-million line address files that are delimited that way. "Comma Separated Value" is actually a bit of a misnomer. Any character can be used. In Excel, you just say "hey this is a pipe delimited file" and away you go albeit with a few extra mouse clicks required.
If you really want a "solid CSV file", using an actual comma for the field delimiter, I would use the Perl CSV module.
Anyway, I think something like this is similar to your code.
## untested ## my @tables = qw (tb1 tb2 tb3); # DBI CONNECTION my $dbh = DBI->connect("dbi:Ingres:$dbname","$user","",{RaiseError => + 1}) or die "Could not connect to database $dbname\n"; foreach my $table (@tables) { my $get_table = $dbh->prepare("SELECT * FROM $table"); $get_table->execute(); my $table_ref = $get_table -> fetchall_arrayref; open my $file, ">", "CSV$table.csv" or die "unable to open CSV$tabl +e.csv for writing $!"; print $file join(",", @{$table_ref->{NAME}}),"\n"; #show header - I +'m not sure this works. print $file join(',',@$_),"\n" for @$table_ref; close $file; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Multiple queries on DBI corresponding to multiple csv files?
by jtech (Sexton) on Feb 20, 2019 at 14:32 UTC | |
by Marshall (Canon) on Feb 22, 2019 at 00:45 UTC |