使用顺心mysqldb
必须使用in
声明如何在声明MySQLdb的
execute('select * from test where id in(%s)','1,2,3')
会得到querysql="select * from test where id in ('1,2,3')"
这aparently是不是我想要的没有abvious方式。现在我必须多次使用execute
方法并将fetchall
结果结合在一起。
有没有更好的方法来做到这一点?
使用顺心mysqldb
必须使用in
声明如何在声明MySQLdb的
execute('select * from test where id in(%s)','1,2,3')
会得到querysql="select * from test where id in ('1,2,3')"
这aparently是不是我想要的没有abvious方式。现在我必须多次使用execute
方法并将fetchall
结果结合在一起。
有没有更好的方法来做到这一点?
试试这个:
data = [1,2,3] # stores the data
in_part = ','.join(['%s'] * len(data)) # prepares formatting string
execute('select * from test where id in(' + in_part + ')', data)
如果你有数字的列表,你可以使用这个:
execute('select * from test where id in ({0},{1},{2})'.format(1, 2, 3))
# query 'select * from test where id in (1,2,3)'
如果在另一方面,你有一个字符串使用:
execute('select * from test where id in ({0})'.format('1, 2, 3'))
# query 'select * from test where id in (1, 2, 3)'
我很遗憾地通知你,但这是一个坏主意。是否知道为什么'execute()'中有第二个参数?请参阅http://www.python.org/dev/peps/pep-0249/另外,您的解决方案不支持可变长度序列。 – Tadeck 2012-03-23 05:59:33
好,格式很明显需要填写数字,谢谢你仍然 – bigwesthorse 2012-04-10 09:07:26
我的错误家伙。感谢Tadeck指出。我只是在寻找字符串连接。 – satran 2012-04-12 07:28:24
哇,它的工作原理,这是一个好主意,它是 – bigwesthorse 2012-03-23 03:26:40