2015-12-09 98 views
1

我有包含id和字符串變量的整數列表。如何在SQL語句中使用這些變量?如果我使用這個:Python中的SQL語句中的變量

list_of_ids = [1,2,3] 
s_date = '2015-01-01' 

cursor.execute(""" 
    SELECT * FROM foo WHERE id IN (%s) 
    AND start_date=%s 
    """, (list_of_ids,s_date)) 

list_of_ids將被括在不應該是的引號中。

此問題與此imploding a list for use in a python MySQLDB IN clause有關,但只有IN語句部分。

我正在使用psycopg2連接 - 如果有幫助。

+0

請參見上的[相關問題]頂端回答(http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in -php?rq = 1),它有_correct_方法的詳細說明。 – Turophile

回答

0

構建parameters作爲一個序列(在下面的例子中的一個列表)。您需要相應地調整sql部分。

in_part = ','.join('%s' for _ in list_of_ids) 
sql = "SELECT * FROM foo WHERE id IN (%s) AND start_date=%%s" % (in_part,) 
params = list_of_ids + [s_date] # [1, 2, 3, '2015-01-01'] 
cursor.execute(sql, params) 
0

Adaptation of Python values to SQL types

要使用in語法投列表中一個元組:

list_of_ids = [1,2,3] 
s_date = '2015-01-01' 

query = """ 
    select * 
    from foo 
    where id in %s and start_date = %s 
""" 
print cursor.mogrify(query, (tuple(list_of_ids), s_date)) 
#cursor.execute(query, (tuple(list_of_ids), s_date)) 

輸出:

select * 
from foo 
where id in (1, 2, 3) and start_date = '2015-01-01' 

要通過列表而不鑄造使用= any語法:

query = """ 
    select * 
    from foo 
    where id = any (%s) and start_date = %s 
""" 
print cursor.mogrify(query, (list_of_ids, s_date)) 
#cursor.execute(query, (list_of_ids, s_date)) 

輸出:

select * 
from foo 
where id = any (ARRAY[1, 2, 3]) and start_date = '2015-01-01'