【问题标题】:escape quote in django extra clausedjango 附加条款中的转义引号
【发布时间】:2016-05-05 15:52:25
【问题描述】:

在Django中,如下语句

entity_name = "a string with a ' quote"
Fiche.objects.extra(where=["'%s' LIKE fiche_name+'%s' " % (entity_name,'%%')])

导致数据库错误:

DatabaseError: ('42000', '[42000] [FreeTDS][SQL Server]Statement(s) could not be prepared. (8180) (SQLExecDirectW)')

如果我打印发送到 db 后端的 sql,我会看到如下内容:

... 'a string with a ' quote' LIKE fiche_name+'%%'

所以我尝试用反斜杠转义字符串中的引号

entity_name = "a string with a \\\' quote"

这一次,查询似乎为 DB 后端做好了充分的准备(引号已转义):

... 'a string with a \' quote' LIKE fiche_name+'%%'

但这会导致相同的数据库错误。

有人知道如何正确地转义引用吗?

编辑:我找到了解决问题的方法:我将字符串中的每个引号替换为两个引号,现在可以使用:

entity_name = entity_name.replace("'","''")

【问题讨论】:

    标签: sql django escaping


    【解决方案1】:

    为时已晚,但正确的做法是将变量作为参数传递给.extra()

    entity_name = "a string with a ' quote"
    Fiche.objects.extra(where=["%s LIKE fiche_name + '%%'")], params=[entity_name])
    

    注意:您所做的与通常所做的相反 (field LIKE 'pattern%'),但仍有可能。另请注意,这是特定于数据库的代码,并非所有数据库都使用 + 作为字符串连接器(您可能需要将其切换为 ||CONCAT())。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      相关资源
      最近更新 更多