【问题标题】:Escape + Quotation in PythonPython中的转义+引号
【发布时间】:2019-04-30 03:06:47
【问题描述】:

我想要做的是将转义字符放在 python 字符串中。让我解释一下。

我得到了字符串

str = 'station and the "Tren Bach"'

这个str 然后被格式化成大的“SQL”查询,由于“Tren Bach”中间的双引号导致malformed exception

所以我尝试在格式化之前进行预处理,如下所示。

str = str.replace ('"', '\"')
sql.format(str)

但是在 sql 字符串中,没有转义。

第二次我尝试了,

str = str.replace ('"', '\\"')
sql.format (str)

但此时,sql中出现了双重转义。

我的预期如下。

str = 'station and the \"Tren Bach\"'

这样str就不会在sql语句中出问题了。

你会推荐其他方式吗?

【问题讨论】:

  • 尝试使用str.replace('"', r'\"') 并在您的SQL 中使用它。看看这是否有效。
  • 旁注:您正在覆盖示例中的 str 内置类型。
  • 哦,不。我使用其他变量名。我只是为解释做了一个伪代码。很抱歉造成混乱。
  • 您应该使用游标的execute() 方法提供的参数化,而不是自己构建查询。其他一切都会导致 SQL 注入漏洞。
  • @zedfoxus 您的建议无效。它使 \\ 对我来说是双重转义。

标签: python python-3.x string replace


【解决方案1】:

BigQuery 使用 slightly different escaping 然后是标准 SQL。您需要在查询中使用引号将值括起来,类似于 Python。例如:

s = '''SELECT ... WHERE my_field='station and the "Tren Bach"' '''
#               note quotes here ^                  and here ^

【讨论】:

    猜你喜欢
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多