如何将不同数量的变量包含到 sql IN 语句中?

How to include varying count of variables into a sql IN statement?

我有许多变量(每次执行脚本时计数都不同)。我需要将这些变量插入到 sql 语句中。例如,让我们假设 sql 语句为:

select * from customer where customer_id in (...);

那些虚线中出现的将是我的变量。如果我知道变量的数量,我可以这样做:

query='''create table xyz as 
         select * from customer where customer_id in (?,?);'''
cursor.execute(query,var1,var2)
query='select * from xyz;'
xyz_details=pd.read_sql(query,con)

但是由于计数不同,我不能保持固定数量的'?'在我的查询中。它可以是一个 运行 中的 2 个和另一个中的 4 个。该脚本确实将计数存储在变量 'cnt' 中。所以如果 cnt 是 4,我有 var1,var2,var3,var4 作为参数,我需要有 4 '?'在我的查询中。

但是,由于这些计数不断变化,我无法在查询中确定一个确定的值,我正在研究如何继续。

如有任何意见,我们将不胜感激!

也许你可以尝试类似的东西?

list_args = [var1, var2, ..., varn]
query='''create table xyz as 
         select * from customer where customer_id in ({});'''.format(','.join('?' * len(list_args)))
cursor.execute(query,var1,var2)
query='select * from xyz;'
xyz_details=pd.read_sql(query,con)