【问题标题】:Placeholders for LIKE operator in postgresql and python [duplicate]postgresql和python中LIKE运算符的占位符[重复]
【发布时间】:2019-10-19 12:41:25
【问题描述】:

不确定如何在不损害 LIKE 运算符功能的情况下消除类型错误 - 即表示在开头、结尾或始终查找字符串的 %。

尝试搜索具有可变字符 380X 的书籍的 isbns。

摆脱 % 以修复类型错误返回一个空列表。

isbn = request.form.get("search")
# Search the database for matching or part matching string, isbn, title, or author
book = db.execute("SELECT * FROM books WHERE isbn LIKE '%:isbn%'", {"isbn":str(isbn)}).fetchall()

预期:书籍及其列的列表,但我收到此错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) 语法 在“380”或附近出现错误 LINE 1: SELECT * FROM books WHERE isbn LIKE '%'380'%' ^

[SQL: SELECT * FROM books WHERE isbn LIKE '%%%(isbn)s%%']

【问题讨论】:

  • 占位符的操作与字符串插值不同(这就是为什么它们更安全地免受 SQL 注入攻击)。您最好的选择可能是传入一个包含 % 的字符串。类似...LIKE :isbn", {"isbn": '%' + str(isbn) + '%'}).fetchall()
  • 谢谢,这个解决了。我不知道您可以将 % 传递给它。

标签: python postgresql


【解决方案1】:

您可以像这样连接 %: db.execute("SELECT * FROM books WHERE isbn LIKE '%%' || %(isbn)s || '%%', {"isbn":str(isbn)})

请注意,在使用命名参数时使用 %% 而不是 %,至少在 psycopg2 中是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 2022-01-25
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多