【问题标题】:Psycopg2 - Passing variable in the where clausePsycopg2 - 在 where 子句中传递变量
【发布时间】:2020-06-11 10:28:19
【问题描述】:

我正在尝试在 Python 中运行 SQL 脚本,其中我在 where 子句中传递了一个变量,如下所示:

cursor.execute(f"""select * from table where type = variable_value""")

在上述查询中,variable_value 具有我试图在 where 子句中使用的值。但是我收到一个错误psycopg2.errors.UndefinedColumn: column "variable_value" does not exist in table

【问题讨论】:

    标签: python amazon-redshift psycopg2


    【解决方案1】:

    根据 psycopg2 文档,execute 函数将变量作为额外参数。

    cursor.execute("""select * from table where type = %(value)s """, {"value": variable_value})
    

    psycopg2 user manual. 中有更多示例。

    另外请仔细阅读关于SQL injection 的部分 - 要点是,您不应该在查询中引用参数,execute 函数会处理这一点,以防止注入有害的 SQL。


    还要解释您遇到的错误 - 您发送的查询是比较两个标识符(typevariable_value)。 table 不包含 variable_value 列,因此出现错误。

    我相信,您打算使用string interpolation 来构造查询,但您忘记了{}。它会像这样工作:

    cursor.execute(f"""select * from table where type = '{variable_value}'""")
    

    ⚠️但因为前面提到过SQL注入,不推荐使用!

    【讨论】:

      猜你喜欢
      • 2022-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 2016-05-18
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      相关资源
      最近更新 更多