Mad_Mac has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to pull some data from a SQLite DB, where I need to execute very similar queries several times. Specifically, I want to pull the list of distinct values out of 3 different columns. I then want to be able to push the list of distinct values into their own arrays, so I can molest them later.
The brute force way to do it is:
# query to get Centers $cent_sth=$dbh->prepare("SELECT DISTINCT Center FROM People"); $cent_sth->execute() or die "Failed to retrieve list of centers from d +atabase. $DBI::errstr"; print " Centers are:\n"; while (@centers = $cent_sth->fetchrow_array()) { print "\t@centers[0]\n" unless (@centers[0]!~/^\d{2} -/); } # query to get Divsions $div_sth=$dbh->prepare("SELECT DISTINCT Div FROM People"); $div_sth->execute() or die "Failed to retrieve list of centers from da +tabase. $DBI::errstr"; print " Divisions are:\n"; while (@divs = $div_sth->fetchrow_array()) { print "\t@divs[0]\n"; } # query to get Departments $dept_sth=$dbh->prepare("SELECT DISTINCT Dept FROM People"); $dept_sth->execute() or die "Failed to retrieve list of centers from d +atabase. $DBI::errstr"; print " Departments are:\n"; while (@depts = $dept_sth->fetchrow_array()) { print "\t@depts[0]\n"; }
I think I ought to be able to do the same thing by looping over the same code 3 times. Something like:
my %orgs = ("Center", "cent_sth", "Div", "div_sth", "Dept", "dept_sth" +) while (($name, $this_sth)=each (%orgs)){ $this_sth=$dbh->prepare("SELECT DISTINCT $name FROM People"); $this_sth->execute() or die "Failed to retrieve list of $name from + database. $DBI::errstr"; }
But I'm pretty sure I'm not naming my statement handlers in a way that will allow me to use them later. What's the smart way to do this?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Looping over multiple queries
by JavaFan (Canon) on Jan 28, 2010 at 15:23 UTC | |
by Mad_Mac (Beadle) on Jan 28, 2010 at 19:35 UTC | |
by Mad_Mac (Beadle) on Jan 28, 2010 at 19:45 UTC | |
by JavaFan (Canon) on Jan 28, 2010 at 19:57 UTC | |
by Anonymous Monk on Jan 28, 2010 at 19:41 UTC | |
by Mad_Mac (Beadle) on Jan 28, 2010 at 19:50 UTC | |
|
Re: Looping over multiple queries
by ww (Archbishop) on Jan 29, 2010 at 00:11 UTC | |
by DStaal (Chaplain) on Jan 29, 2010 at 14:35 UTC |