如何在mysqldb中使用语句

时间:2012-03-22 09:41:59

标签: python mysql-python

Seemed mysqldb没有明确的方式来使用in声明

execute('select * from test where id in(%s)','1,2,3')

将获得querysql="select * from test where id in ('1,2,3')"

这显然不是我想要的。现在,我必须多次使用execute方法并将fetchall结果附加在一起。

有没有更好的方法呢?

2 个答案:

答案 0 :(得分:2)

试试这个:

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)

答案 1 :(得分:0)

如果你有一个数字列表,你可以使用它:

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)'

通常使用format()函数来操作字符串。请阅读官方文档herehere中的详情。

相关问题