2012-03-22 33 views
1

使用順心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結果結合在一起。

有沒有更好的方法來做到這一點?

回答

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

哇,它的工作原理,這是一個好主意,它是 – bigwesthorse 2012-03-23 03:26:40

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中詳細瞭解它。

+0

我很遺憾地通知你,但這是一個壞主意。是否知道爲什麼'execute()'中有第二個參數?請參閱http://www.python.org/dev/peps/pep-0249/另外,您的解決方案不支持可變長度序列。 – Tadeck 2012-03-23 05:59:33

+0

好,格式很明顯需要填寫數字,謝謝你仍然 – bigwesthorse 2012-04-10 09:07:26

+0

我的錯誤傢伙。感謝Tadeck指出。我只是在尋找字符串連接。 – satran 2012-04-12 07:28:24