开发者

Parameterizing 'SELECT IN (...)' queries

I want to use MySQLdb to create a parameterized query such as:

serials = ['0123456', '0123457']
c.execute('''select * from table where key in %s''', (serials,))

But what ends up being send to the DBMS is:

select * from table where key in ("'0123456'", "'0123457'")

Is it possible to create a parameterized query like this? Or do I have to loop myself and build up a result set?

Note: executemany(...) won't work for this - it'll only return the last result:

>>> c.executemany('''select * from table where key in (%s)''',
        [ (x,) for x in serials ] )
2L
>>> c.fetchall()
((1, '0123457', 'faketestdata'),)

Final solution adapted from Gareth's clever answer:

# Assume check above for case where len(serials) == 0
query = '开发者_JS百科''select * from table where key in ({0})'''.format(
    ','.join(["%s"] * len(serials)))
c.execute(query, tuple(serials)) # tuple() for case where len == 1


You want something like this, I think:

query = 'select * from table where key in (%s)' % ','.join('?' * len(serials))
c.execute(query, serials)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜