in reply to Simple DBI question, select rows based on an array

Filling in the missing pieces in the approach suggested by Gangabass above:
#!/usr/bin/perl use strict; use DBI; my $dbh = DBI->connect( ... ); my @val1_set = qw/foo bar baz quz/; my $sth = $dbh->prepare("select val1,val2,val3 from atable where val1= +?"); my @result_set; for my $val ( @val1_set ) { $sth->execute( $val ); my $result = $sth->fetchall_arrayref; push @result_set, $result; } for my $i ( 0 .. $#val1_set ) { print "Results for val1=$val1_set[$i]:\n"; if ( ref( $result_set[$i] ) ne "ARRAY" or @{$result_set[$i]} == 0 ) { print "__EMPTY_SET__\n\n" } else { for my $row ( @{$result_set[$i]} ) { print join("\t", @$row ),"\n" } print "\n"; } }
That will work no matter how many rows get returned (0, 1 or more) on each iteration over the set of "val1" values. For any non-empty return from the execute() call, the "fetchall_arrayref" always returns a reference to an AoA (a set of 1 or more rows, with each row containing a set of 1 or more columns or fields), so you have to dereference the set of rows, and then for each row, dereference the set of columns.

(update: And in this case, since the result set is an array that is built up over some number of execute calls, you are starting with an AoAoA, so the sample code uses $i to iterate over the top-level array.)

Replies are listed 'Best First'.
Re^2: Simple DBI question, select rows based on an array
by novosirj (Initiate) on Nov 05, 2009 at 19:58 UTC
    Thanks, this is very helpful. What was least clear for me is whether, if I have to loop through the array anyway, I should loop through the select and in the same loop print the values, whether I should wait until I've gotten the values and then print them all, or whether there was something like execute_array that would handle them all at the same time. I believe I read that execute_array is not for SELECT statements, though, even though I can't figure out where I'd have read that.