使用“喜欢” 在带有 python (django) 参数的游标/查询中
我知道这可能很愚蠢,但我决定无论如何都要问。
我一直在尝试查询类似的内容:
cursor.execute("select col1, col2 \
from my_tablem \
where afield like '%%s%'
and secondfield = %s
order by 1 desc " % (var1, var2) )
但是我在类似的句子中遇到错误。 它不喜欢额外的 %,我需要额外的 % 来获取包含第一个 %s 值的所有结果。
有想法吗?
蒂亚!
I know this may be something stupid but I decided to ask any way.
I've been trying to query something like:
cursor.execute("select col1, col2 \
from my_tablem \
where afield like '%%s%'
and secondfield = %s
order by 1 desc " % (var1, var2) )
But I get an error in the like sentence. It doesn't like the extra % which I need to get all the results that contains the first %s value.
Ideas?
TIA!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,为什么不使用 Django ORM 来实现此目的?
其次,确保您得到了您期望的 SQL。
第三,您的方法存在一个称为 SQL 注入攻击的安全漏洞。 你真的不应该像这样执行 SQL。
如果您绝对必须在 Django ORM 之外执行操作,则必须在查询中使用绑定变量,而不是字符串替换。 请参阅 http://docs.djangoproject.com /en/dev/topics/db/sql/#performing-raw-sql-queries。
First, why aren't you using the Django ORM for this?
Second, be sure you're getting the SQL you expect.
Third, your method has a security hole called a SQL Injection Attack. You really should not be doing SQL like this.
If you absolutely must do things outside Django's ORM, you have to use bind variables in your query, not string substitution. See http://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-sql-queries.
可以将字符串“%”破解为搜索字符串吗?
can hack string '%' into search string?
我有类似的问题。 我试图在串联的名称字段中进行搜索。 我的查询是这样的:
问题是 %% 破坏了我的查询。 我最终得到的解决方案是:
I had a similar issue. I was trying to search among concatenated name fields. My query was something like:
The problem was that the %% were breaking my query. The solution I wound up with was:
(Postgresql 9.1)
(Postgresql 9.1)