in reply to Re^2: Multiple queries on DBI corresponding to multiple csv files?
in thread Multiple queries on DBI corresponding to multiple csv files?
Good stuff!
I have created the Menu and it is accepting params so, it works fine when the id is typed, but it doesn't work when it is left blank ""
I am struggling with this error message: Can't locate object method "selectall_array" via package "DBI::db" at ./test.pl line 60.
Well, that is the line 60: @id = map{ $_->[0] } $dbh->selectall_array($sql,undef,'no');
what am I doing wrong here?
#!/usr/bin/perl -W use DBI; use Text::CSV_XS; # GLOBALS @id = ""; $dbname = ""; $user = ""; # MAIN MENU # Don't allow duplicated arguments and blank/undef arguments # except for id (in this case blank/undef id means all ids) foreach my $arg (@ARGV) { if ($arg eq '-h' || $arg eq '--help') { die "Script usage manual here\n"; exit; } if ($arg =~ /^(\w+)$/) { die "Error: Multiple databases: $dbname and $arg." if $dbname; $dbname = $1 ; next; } if ($arg =~ /^--?u(\w+)$/) { die "Error: Multiple users $user and $arg." if $user; $user = $1 ; next; } if ($arg =~ /^--?id(\d+)$/) { die "Error: Multiple ids specified: -id$id[0] and $arg.\n" if +$id[0]; $id[0] = $1 ; next; } elsif ($arg =~ /^--?id(\S+|)$/) { die "Error id format, use -id<integer>\n"; } } die "No database, type <dbname>\n" unless $dbname; die "No username, use -u<username>\n" unless $user; # DBI CONNECTION my $dbh = get_dbh(); # EXEC if ($id[0] eq "") { my $sql = "SELECT DISTINCT id from mytable WHERE active = ?"; @id = map{ $_->[0] } $dbh->selectall_array($sql,undef,'no'); } for my $id (@id) { my @query = ( ["SELECT id FROM mytable WHERE id=? AND salary >= 1","csvfile1 +_$id.csv"], ["SELECT name FROM mytable WHERE id=? AND salary >= 1","csvfile2 +_$id.csv"], ["SELECT salary FROM mytable WHERE id=? AND salary >= 1","csvfile3 +_$id.csv"], ["SELECT dept FROM mytable WHERE id=? AND salary >= 1","csvfile4 +_$id.csv"], ); for (@query) { run_query(@$_,$id); } } # SUBROUTINES sub get_dbh { my($dbh) = DBI->connect("dbi:IngresII:$dbname","$user","") or die "Could not connect to database $dbname\n"; return $dbh; } sub run_query { my ($sql, $csvfile, $id) = @_; print "Running $sql for $id\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($id); $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"; }
|
|---|