Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: how do i construct a sql select statement, where i want to get the where clauses out of an array

by chipmunk (Parson)
on Aug 25, 2001 at 23:48 UTC ( [id://107854]=note: print w/replies, xml ) Need Help??


in reply to how do i construct a sql select statement, where i want to get the where clauses out of an array

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).

  • Comment on Re: how do i construct a sql select statement, where i want to get the where clauses out of an array
  • Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://107854]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-19 03:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found