我已经引用了这些帖子 1 , 2 。我不确定我是否错误地使用了这些帖子中的建议。
基本上,我想在 postgresql 查询中使用我的 pandas 列表(用 Jupyter 笔记本编写)
id_list = [1,2,3,4]
我想在下面的查询中使用我的id_list
。我尝试了以下 2 个选项
选项1
df_q = pd.read_sql('select * from tablea where subject_id in {id_list}', con=conn)
选项2
cur.execute("select * from tablea where subject_id in %s", id_list)
这里的专家可以帮我解决如何在查询中直接使用python变量吗?
最佳答案
处理 IN
子句的正确方法是单独构建占位符子句,然后使用参数替换将列表元素绑定(bind)到查询:
sql = "select * from tablea where subject_id in ({})"
# Create a string like "%s, %s, %s" with one "%s" per list element
placeholders = ', '.join(['%s'] * len(id_list))
sql = sql.format(placeholders)
# Use parameter substitution to bind values to the query
cur.execute(sql, id_list)
如果值被错误转义,使用字符串格式化或连接(包括 f 字符串)可能会导致错误,或者在最坏的情况下使数据库遭受 SQL 注入(inject)攻击。
关于python - 使用 pandas list 使用 postgresql 查询过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68066426/