Python中SQL语句中的变量

时间:2015-12-09 03:47:12

标签: python sql postgresql psycopg2

我有包含id的整数列表和一个字符串变量。如何在SQL语句中使用这些变量?如果我用这个:

{{1}}

list_of_ids将用引号括起来,不应该是引号。

此问题与此imploding a list for use in a python MySQLDB IN clause有关,但只与IN语句部分有关。

我使用psycopg2连接 - 如果有帮助的话。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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'