【问题标题】:Use pandas list to filter data using postgresql query使用 pandas 列表使用 postgresql 查询过滤数据
【发布时间】:2021-09-05 00:53:00
【问题描述】:

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

基本上,我想在 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变量吗?

【问题讨论】:

    标签: python sql pandas postgresql psycopg2


    【解决方案1】:

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

    【讨论】:

    • print(cur.mogrify(sql, id_list)) 的结果是什么?
    • 我修好了。这是一个不相关的问题。我可以知道mogrify 代表什么吗?
    • 它打印将发送到数据库 psycopg.org/docs/cursor.html#cursor.mogrify 的查询(假设您使用的是 psycopg2,我应该检查一下 :-)
    【解决方案2】:

    如果你想在 python 中使用字符串中的变量,你只需在字符串的开头添加f 就可以了

    df_q = pd.read_sql(f'select * from tablea where subject_id in {id_list}', con=conn)

    这将被翻译成 'select * from tablea where subject_id in [1, 3, 4]'

    【讨论】:

    • 但是,Postgresql 不使用[ 来表达列表。您可能希望将列表转换为元组,因为它使用(df_q = pd.read_sql(f'select * from tablea where subject_id in {tuple(id_list)}', con=conn)
    • 使用字符串格式将值绑定到 SQL 查询容易出错并且存在安全风险。请不要这样做。
    猜你喜欢
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 2013-12-13
    • 2022-12-17
    • 2019-08-08
    相关资源
    最近更新 更多