psycopg2 奇怪的行为
from django.db import connection
q = 'some value'
sql1 = 'SELECT * FROM table WHERE field LIKE %%%s%%' % q
sql2 = 'SELECT * FROM table WHERE field LIKE %%'+ q +'%%'
cursor = connection.cursor()
cursor.execute( sql1 ) #why exception: IndexError: tuple index out of range ?
cursor.execute( sql2 ) #works ok
from django.db import connection
q = 'some value'
sql1 = 'SELECT * FROM table WHERE field LIKE %%%s%%' % q
sql2 = 'SELECT * FROM table WHERE field LIKE %%'+ q +'%%'
cursor = connection.cursor()
cursor.execute( sql1 ) #why exception: IndexError: tuple index out of range ?
cursor.execute( sql2 ) #works ok
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要正确引用您的 SQL 参数。
正确引用我的意思是使用 DBAPI 提供的引用工具,而不是在字符串周围添加 ' ,这是没有用的。
正确的代码:
真正正确的代码:
假设 q = "a'bc"
首先,将其重写为“%a'bc%”
然后将其用作普通字符串参数。 psycopg 会将其重写为 '%a\'bc%' 。
如果 q 可能包含“%”并且您想搜索它,则使用第二个。
You need to QUOTE properly your SQL arguments.
And by quoting properly I mean using the quote facility provided by DBAPI, not adding a ' around your string, which is useless.
Correct code :
Really correct code :
Suppose q = "a'bc"
First, rewrite this as "%a'bc%"
Then use it as a normal string argument. psycopg will rewrite it as '%a\'bc%' as it should.
If q may contain "%" and you want to search for it, then use the second one.
使用直接字符串操作几乎肯定会导致不正确的 SQL,从而容易受到 SQL 注入攻击 (请参阅 psycopg2 关于该主题的评论)。
我认为你想做的是尝试在 django 中执行 LIKE '%some value%',对吧?:
从 psycopg2 2.4.1 开始,在服务器上执行的 SQL 是:
Using direct string manipulation will almost certainly lead to improper SQL that is vulnerable to SQL Injection attacks (see psycopg2's comments on the subject).
What I think you're looking to do is try and perform a LIKE '%some value%' in django, right?:
As of psycopg2 2.4.1, the SQL that is executed on the server is:
您需要正确引用 SQL 命令:
正确引用是指在
LIKE
表达式中使用单引号。You need to QUOTE properly your SQL command:
And by quoting properly I mean using single quotes with
LIKE
expressions.