参数化'SELECT IN(...)'查询

时间:2010-11-17 18:26:49

标签: python mysql

我想使用MySQLdb创建参数化查询,例如:

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

但最终发送给DBMS的是:

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

是否可以像这样创建参数化查询?或者我是否必须循环自己并构建结果集?

注意:executemany(...)不适用于此 - 它只返回最后一个结果:

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

最终解决方案改编自Gareth的聪明答案:

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

1 个答案:

答案 0 :(得分:3)

你想要这样的东西,我想:

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