You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyAthena中如何将Python列表作为SQL的IN查询条件传入

报错原因

你原写法存在两个问题:

  • 不能直接将list类型和字符串用+拼接,类型不匹配会触发类型错误
  • 三引号拼接语法错误,引号位置混乱,语法解析失败

正确实现方式

方式1:直接格式化拼接(适合内部工具、确认输入无注入风险的场景)

如果customer是数值类型字段:

customer_list = [123,567,494]
# 把列表元素转成字符串后用逗号拼接
in_condition = ','.join(map(str, customer_list))
my_query = f"""
select * from my_table
where customer in ({in_condition})
order by name
"""

如果customer是字符串类型字段,需要给每个元素包裹单引号:

customer_list = ["user1", "user2", "user3"]
in_condition = ','.join([f"'{x}'" for x in customer_list])
my_query = f"""
select * from my_table
where customer in ({in_condition})
order by name
"""

方式2:参数化查询(优先推荐,避免SQL注入风险)

PyAthena遵循Python DB API规范,用占位符的方式传入列表参数更安全:

from pyathena import connect

customer_list = [123,567,494]
# 生成和列表长度匹配的占位符
placeholders = ','.join(['%s'] * len(customer_list))
my_query = f"""
select * from my_table
where customer in ({placeholders})
order by name
"""

# 执行查询时把列表作为参数传入
conn = connect(aws_access_key_id='你的AK', aws_secret_access_key='你的SK', region_name='区域')
cursor = conn.cursor()
cursor.execute(my_query, customer_list)
# 获取结果
result = cursor.fetchall()

内容的提问来源于stack exchange,提问作者Minfetli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:42:03