gpt4 book ai didi

postgresql - 在 PostgreSQL 中使用 LIKE '%a%' 同时针对 SQL 注入(inject)清理数据

转载 作者:行者123 更新时间:2023-12-04 09:54:26 32 4
gpt4 key购买 nike

您好,我正在尝试使用 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在标题通配符之后。但我不知道这是否是故意的,所以我把它留在了我的例子中。

关于postgresql - 在 PostgreSQL 中使用 LIKE '%a%' 同时针对 SQL 注入(inject)清理数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61953790/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com