dbapi2 select where IN (...)

Duncan Booth duncan.booth at invalid.invalid
Mon Nov 30 10:46:02 EST 2009


Gerhard Häring <gh at ghaering.de> wrote:

>> execute("""SELECT * FROM table WHERE num IN ?;""" ,
>> ((2,3,8,9),))    ...fail... [...]
> 
> You cannot use parameter binding when the number of parameters is
> unknown in advance. So you'll have to create this part of the SQL query
> differently.
> 
> For example:
> 
> ids = [2, 3, 8, 9]
> in_clause = " (" + ",".join([str(id) for id in ids]) + ")"
> query = "select * from table where num in" + in_clause
> 
You can use parameter bindings when you don't know the number of parameters 
in advance. Just don't create the query string until  you do know the 
number of parameters:

ids = [2, 3, 8, 9]
query = "select * from table where num in (%s)" % ','.join('?'*len(ids))
execute(query, ids)


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list