你好,有IM试图运行一个postgresql查询在flask上使用SQLAlchemy,但我不明白我怎么能保持我的查询消毒,而使用LIKE'%'参数。
db.execute("SELECT * FROM books WHERE isbn LIKE '%:isbn%' OR title LIKE '%:title%L' OR author = '%:author%'", {"isbn": isbn, "title": title, "author": author})
这就是我得到的结果,但当然不能运行.我不想牺牲系统的完整性来允许使用LIKE。
有没有人有一个建议给我?
在SQL表达式中,参数占位符不能在引号字符串内。否则就无法在SQL中使用看起来像占位符的字符作为文字字符串。
所以你必须将占位符放在引号字符串之外,并与通配符一起用 ||
串联运算符.
db.execute("""SELECT * FROM books
WHERE isbn LIKE '%'||:isbn||'%'
OR title LIKE '%'||:title||'%L'
OR author LIKE '%'||:author||'%'""",
{"isbn": isbn, "title": title, "author": author})
另一种方法是将参数的值与 %
在Python中使用SQL通配符,然后将生成的字符串作为参数传递。在这种情况下,你可以跳过在查询中放入通配符。还是不要把参数占位符放在SQL表达式的字符串引号里面。
db.execute("""SELECT * FROM books
WHERE isbn LIKE :isbn
OR title LIKE :title
OR author LIKE :author""",
{"isbn": "%"+isbn+"%", "title": "%"+title+"%L", "author": "%"+author+"%"})
P.S.: 我编辑了你的 author =
到 author LIKE
因为你不能使用通配符与 =
.
而且我觉得你有一个额外的 L
在标题通配符之后。但我不知道这是不是有意为之,所以我在例子中留了下来。