2015-06-02 21 views
0

在Python 2.7,我能做到一個參數傳遞給一個SQL命令是這樣的:傳遞數組參數設置爲SQL命令

cursor.execute("select * from my_table where id = %s", [2]) 

我不能得到的陣列相當於像這樣的工作:

cursor.execute("select * from my_table where id in %s", [[10,2]]) 

顯然,我可以做字符串格式化,但如果可能的話,我想要做一個適當的參數。如果有問題,我使用postgresql數據庫。

+1

'我想盡可能做一個合適的參數 - 你是什麼意思? – thefourtheye

+0

''select * from my_table where where id in(%d,%d)「,[10,2]) ''有什麼問題? –

+0

該列表並非固定大小。 %d也可以使用常規的python字符串格式,但在這種情況下它不起作用。 – clay

回答

2
cursor.execute("select * from my_table where id = ANY(%s);", [[10, 20]]) 

參見note。要使用IN,請參閱section below

cursor.execute(cursor.mogrify("select * from my_table where id in %s", 
           [tuple([10, 20])])) 
+0

原因是'IN(1,2,3)'在任何地方都沒有數組,而是一組字面值。 –