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


In reply to Re: how do i construct a sql select statement, where i want to get the where clauses out of an array by chipmunk
in thread how do i construct a sql select statement, where i want to get the where clauses out of an array by pitbull3000

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.