in reply to Multiple queries on DBI corresponding to multiple csv files?
I have included some features and still a bit redundant on the condition "if id exists", it is ok for now and open to suggestions.
This is the result:
#!/usr/bin/perl -W # This script will create multiple csv files based on # passed arguments "id" and custom "where" clause. Also, # in the future it will read and display it as # floating boxes in an HTML page (D3JS does the trick) use DBI; use Text::CSV_XS; # Constant: # my $htmlpage = "htmlfile_$id"; #TODO: it will build the html file # Here are the temporary params (TODO: it will use @ARGV) # This is an important param because it will run bunch of queries # just for the provided id, if no id was provided then # it will run the queries for all ids from the table my $id = ""; # DBI CONNECTION my $dbh = get_dbh(); # SUBROUTINES sub run_query { my ($sql, $csvfile) = @_; print "Running $sql\n"; open my $fh, '>', $csvfile or die "Could not open $csvfile: $!"; my $csv = Text::CSV_XS->new ({ binary => 1, eol => "\n" }); my $sth = $dbh->prepare ($sql); $sth->execute; $csv->print($fh, $sth->{NAME_lc}); my $count = 1; while (my $row = $sth->fetchrow_arrayref) { $csv->print($fh, $row); ++$count; } close $fh; print "ID: $id, $count lines dumped to $csvfile\n"; } sub get_dbh { my $dbname = "jtech"; my $user = "jtech"; my($dbh) = DBI->connect("dbi:IngresII:$dbname","$user","") or die "Could not connect to database $dbname\n"; return $dbh; } # MAIN PROGRAM # If the user type an ID it will generate 4 csv files # that corresponds to each custom SQL query if ($id) { # In this case it generates reports for the typed "id" only $clause = "id=$id AND"; my @query = ( ["SELECT id FROM mytable WHERE $clause salary >= 1","csvfile1_ +$id.csv"], ["SELECT name FROM mytable WHERE $clause salary >= 1","csvfile +2_$id.csv"], ["SELECT salary FROM mytable WHERE $clause salary >= 1","csvfi +le3_$id.csv"], ["SELECT dept FROM mytable WHERE $clause salary >= 1","csvfile +4_$id.csv"], ); for (@query) { run_query(@$_); } } # If there is NO ID provided than it will generate csv files # corresponding to all ids found with a special clause where # active ='no' (all IDs will get 4 csv file) else { # Returns a list of all existents "id" (TO BE UPDATED TO USE DBI) my $cmd = `echo 'SELECT DISTINCT id from mytable\\g\\q' | sql jtec +h -jtech -S | sed -e 's/ //g'`; foreach $cmd (split /[\n\r]+/, $cmd) { $id = $cmd; $clause = "active ='no' AND"; my @query = ( ["SELECT id FROM mytable WHERE $clause salary >= 1","csvfi +le1_$id.csv"], ["SELECT name FROM mytable WHERE $clause salary >= 1","csv +file2_$id.csv"], ["SELECT salary FROM mytable WHERE $clause salary >= 1","c +svfile3_$id.csv"], ["SELECT dept FROM mytable WHERE $clause salary >= 1","csv +file4_$id.csv"], ); for (@query) { run_query(@$_); } } }
|
|---|