【问题标题】:Variables in SQL statement in PythonPython中SQL语句中的变量
【发布时间】:2015-12-09 03:47:11
【问题描述】:

我有一个包含 id 和一个字符串变量的整数列表。如何在 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 连接——以防万一。

【问题讨论】:

  • 查看related question 上的最佳答案,其中详细描述了正确的方法。

标签: python sql postgresql psycopg2


【解决方案1】:

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)

【讨论】:

    【解决方案2】:

    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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-21
      • 2010-10-28
      相关资源
      最近更新 更多