在 PostgreSQL 中使用 LIKE '%a%' 同时再次清理数据 SQL 注入

Using LIKE '%a%' in PostgreSQL while sanitizing data agains SQL injections

你好,我正在尝试 运行 使用 SQLAlchemy 在 Flask 上进行 postgresql 查询,但我不明白如何在使用 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.

中使用看起来像占位符的字符作为文字字符串

因此您必须将占位符放在带引号的字符串之外,并使用 || string concatenation operator.

与通配符连接
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。但我不知道这是不是故意的,所以我把它留在了我的例子中。