我如何在python sql中传递值列表?

时间:2019-05-02 12:27:59

标签: python sql

我正在传递 IN 查询中的值列表。当我在工作台和其他地方运行此查询时,它正在工作,但在python代码内部却不工作。

在python中,它将值作为列表,因此出现错误。

我想在Python SQL查询中传递值列表。但这给了我一个错误:

  

只能将str(而不是“ tuple”)连接到str

我也尝试使用该列表,但随后出现错误:

  

只能将str(而不是“ list”)连接到str

emp_id = ['470224', '471822', '470551', '471854', '471603', '468121', '458435', '466700', '471605', '471609', '471604', '458535', '454387', '469881']

mycursor.execute("select * from table_name where id in "+"'"+emp_id+"'")

查询必须按如下方式工作:

select * from table_name where id in ('470224', '471822', '470551', '471854', '471603', '468121', '458435', '466700', '471605', '471609', '471604', '458535', '454387', '469881') ;

它必须获取IN查询中的所有记录。

1 个答案:

答案 0 :(得分:0)

emp_id = ['470224', '471822', '470551', '471854', '471603', '468121', '458435', '466700', '471605', '471609', '471604', '458535', '454387', '469881']
mycursor.execute("select * from table_name where id in " + str(tuple(emp_id)))