使用 pandas 列表通过PostgreSQL查询过滤数据 [英] Use pandas list to filter data using postgresql query

查看:25
本文介绍了使用 pandas 列表通过PostgreSQL查询过滤数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经引用了这些帖子12。我不确定我是否错误地使用了这些帖子中的建议。

基本上,我希望在PostgreSQL查询中使用我的 pandas 列表(用Jupyter笔记本编写)

id_list = [1,2,3,4]
我想在下面的查询中使用我的id_list。我尝试了以下两个选项

选项-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子句的正确方法是单独构建占位符子句,然后使用参数替换将列表元素绑定到查询:

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注入攻击。

这篇关于使用 pandas 列表通过PostgreSQL查询过滤数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆