【问题标题】:How to add escape with in python """ quote string?如何在 python """ 引号字符串中添加转义?
【发布时间】:2020-07-28 11:28:50
【问题描述】:

我正在尝试集成我的 AWS lambda 函数来查询我的 postgresql。

sql_update_query = """update  "YP_SUPPLIERS" set %s =%s where "YP_SUPPLIERS"."supplierID"= %s"""
    cursor.execute(sql_update_query, (key[0],value[0],supplierID))

显然在创建使用的表“”时。解决这个问题非常忙碌。

错误

syntax error at or near "'supplierName'"
LINE 1: update  "YP_SUPPLIERS" set 'supplierName'='key' where "YP_SU...

似乎设置 %s 的值是供应商名称应该在“”中。 任何人都可以让我知道一个解决方法或者我该如何正确地实现它

【问题讨论】:

  • @MikeOrganek 恐怕它还没有实现那里提到的内容。不过谢谢你:)
  • 是的。确实如此。您收到的错误是因为 supplierName 是列名。当execute 将其替换为参数时,它会将supplierName 视为文字值。
  • @MikeOrganek 那么我怎样才能将供应商名称作为列名。我使用它是因为我不知道要修改的列名。这将从 API 查询参数发送

标签: python python-3.x postgresql lambda


【解决方案1】:

使用 psycopg2 的SQL composition 功能

from psycopg2 import sql

sql_update_query = sql.SQL(
    """update "YP_SUPPLIERS" 
          set {} = %s,
              {} = %s
        where "YP_SUPPLIERS"."supplierID" = %s""").format(
                                                    sql.Identifier(key[0]),
                                                    sql.Identifier(key[1])
                                                   )

cursor.execute(sql_update_query, (value[0], value[1], supplierID))                        

【讨论】:

  • 如果我有多个列要更新,这是否有效?我会添加 """update "YP_SUPPLIERS" set {} = %s set{} = %s where "YP_SUPPLIERS"."supplierID" = %s""").format(sql.Identifier(key[0],key [1]))
  • @sumanthshetty 否。每次格式替换时,您都需要致电 sql.Identifier() 一次。我会更新我的答案。如果您将多个参数传递给sql.Identifier(),那么它会构造一个标识符,如"FirstString"."SecondString"
  • 知道了。非常感谢您的解释,它帮助我更清楚地理解它。
【解决方案2】:

使用这个

sql_update_query = """update  YP_SUPPLIERS set %s =%s where supplierID= %s"""
cursor.execute(sql_update_query%(key[0],value[0],supplierID))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 2017-03-02
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多