Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Can a DBI Placeholder accept multiple values?

by igelkott (Priest)
on Feb 09, 2008 at 23:53 UTC ( #667217=note: print w/replies, xml ) Need Help??


in reply to Can a DBI Placeholder accept multiple values?

Don't think this can be done with standard DBI. Every substitution gets quoted so if you use $var = join',', @ids; and execute with this $var, you'll get ... where id in ('1,2,3,4') and the query will obviously fail. Can't trick DBI by setting the { TYPE => SQL_INTEGER } attribute since it'll recognize it as a string and quote it anyway (and complain about the error).

As an alternative, DBIx-Simple has a "??" placeholder which is replaced with a list of as many question marks as values. Btw, I've only started looking at this module and haven't checked the speed in production.

So, for example, your code fragment might look like:

my @ids = (1,2,3,4); my $query = 'select * from a_table where id in (??)'; my $result = $dbh->query($q, @ids);
The prepare is taken care of internally and rows can be fetched in various ways.

Replies are listed 'Best First'.
Re^2: Can a DBI Placeholder accept multiple values?
by Anonymous Monk on May 13, 2008 at 14:27 UTC
    You would need to replace (?) with the number of array elements e.g $val = " "; for( $j = 0; $j < @id;$j++) $val .= "?,"; } $val = substr($val,0,-1); $query = $dbh->prepare("REPLACE INTO $tbl ($col) VALUES ($val)"); and then $query->execute(@id); works fine (tested with DBI:mysql)
      You would need to replace (?) with the number of array elements

      Yes, the number of (comma-delimited) "?" must equal the number of values to be inserted but the $val .= "?,"; you wrote here would of course end up with an extra comma. There's certainly other ways make this string but that should otherwise work fine.

      As noted, the special "??" placeholder of DBIx-Simple eliminates the need to make the need to make this string of "?,?,?..." (as well as other simplifications).

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2022-05-25 13:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (90 votes). Check out past polls.

    Notices?