Hi Perlmonks,
I am new at the Perl world and this is my first post and script
The below script generates .csv files corresponding to each executed query using DBI but, I am not happy with the code redundancy.
Had to search for some examples but didn't find anything. I would appreciate an example using a hash to understand how it works
Is there any nice way to do it?
Thanks in advance
# Create multiples csv file corresponding to each sql query my $csvfile1 = "csvfile1.csv"; my $csvfile2 = "csvfile2.csv"; my $csvfile3 = "csvfile3.csv"; # DBI CONNECTION my($dbh) = DBI->connect("dbi:Ingres:$dbname","$user","") or die "Could not connect to database $dbname\n"; #tb1 select my ($sth) = $dbh->prepare(SELECT * FROM tb1) or die "Prepare failed: $DBI::errstr\n"; $sth->execute() or die "Prepare failed: $DBI::errstr\n"; #create csvfile1 according to tb1 select open my $fh, ">raw", $csvfile1 or die "$csvfile1: $!"; $fh->print (join(",", @{$sth->{NAME}}), "\n"); #show header while (my @row = $sth->fetchrow_array()) { $fh->print (join(",", @row), "\n"); }; close $fh or die "$csvfile1: $!"; $sth->finish(); #tb2 select my ($sth) = $dbh->prepare(SELECT * FROM tb2) or die "Prepare failed: $DBI::errstr\n"; $sth->execute() or die "Prepare failed: $DBI::errstr\n"; #create csvfile2 according to tb2 select open my $fh, ">raw", $csvfile2 or die "$csvfile2: $!"; $fh->print (join(",", @{$sth->{NAME}}), "\n"); #show header while (my @row = $sth->fetchrow_array()) { $fh->print (join(",", @row), "\n"); }; close $fh or die "$csvfile2: $!"; $sth->finish(); #tb3 select my ($sth) = $dbh->prepare(SELECT * FROM tb3) or die "Prepare failed: $DBI::errstr\n"; $sth->execute() or die "Prepare failed: $DBI::errstr\n"; #create csvfile3 according to tb3 select open my $fh, ">raw", $csvfile3 or die "$csvfile3: $!"; $fh->print (join(",", @{$sth->{NAME}}), "\n"); #show header while (my @row = $sth->fetchrow_array()) { $fh->print (join(",", @row), "\n"); }; close $fh or die "$csvfile3: $!"; $sth->finish(); $dbh->disconnect();
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |