运行SQL查询的Python使用WHERE IN {list}和列表太长

时间:2018-06-01 22:25:06

标签: python sql list pandas

以下是我脚本的一部分:

sql1 = """
                    SELECT distinct th.name, 'MMS' as Status
                    FROM t1 
                    JOIN t2 on t1.id = t2.tid
                    WHERE t2.station= 'MatS'
                    AND t1.name IN ({listthinglist})
        """.format(listthinglist=', '.join("'" + item + "'" for item in list_of_things))
    cur.execute(sql1)

list_of_things包含22016项,我无法在python中运行此查询。是否有替代方法可以在python中运行这样的查询。

1 个答案:

答案 0 :(得分:0)

请不要使用formatexecute函数接受您将列表传递给的“参数”参数。您可以像这样修改它:

sql1 = """
  SELECT distinct th.name, 'MMS' as Status
  FROM t1 
  JOIN t2 on t1.id = t2.tid
  WHERE t2.station= 'MatS'
  AND t1.name IN (%s)
"""
cur.execute(sql1, (list_of_things,))