2015-12-09 131 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'