I like to use placeholders with DBI, for efficiency and robustness. You can prepare a statement once, and use it over and over again with different bind values. However, it's difficult to use placeholders efficiently with the IN() function, because you might not know ahead of time how many values you will want to bind. To deal with this issue, I came up with the following approach:
my @sth;
while (<DATA>) {
my @id = split /,/, $_;
$sth[@id] ||=
$dbh->prepare(
'SELECT id, size FROM table WHERE id IN (' .
join(',', ('?') x @id) . ')'
);
$sth[@id]->execute(@id);
while (my($id, $size) = $sth[@id]->fetchrow_array()) {
print "$id $size\n";
}
}
__DATA__
1,4,6
7,10
9
2,5,8
3
Instead of a single statement handle in $sth, I have an array of statement handles in @sth. After setting up @id, I make sure there's a statement handle prepared with the right number of placeholders. For example, the first time @id has three values, $sth[3] will be undef, so a new statement handle is prepared, with three placeholders, and assigned to $sth[3]. The next time @id has three values, $sth[3] will already hold the proper statement handle.
The statement handle is executed on the next line, with the values in @id bound to the placeholders. The results are fetched and processed, and then the process starts over with new values in @id. Note that @id is in a scalar context in $sth[@id] and ('?') x @id, and a list context in execute(@id).