psycopg2奇怪的行为

cet*_*ver 4 django postgresql psycopg

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
Run Code Online (Sandbox Code Playgroud)

peu*_*feu 6

您需要正确引用您的SQL参数.

通过正确引用我的意思是使用DBAPI提供的引用工具,而不是在你的字符串周围添加一个没用的字符串.

正确的代码:

q = "%"+q+"%"
cursor.execute( 'SELECT * FROM table WHERE field LIKE %s', (q,) )
Run Code Online (Sandbox Code Playgroud)

真正正确的代码:

q = "%"+q.replace("%","%%")+"%"
cursor.execute( 'SELECT * FROM table WHERE field LIKE %s', (q,) )
Run Code Online (Sandbox Code Playgroud)

假设q ="a'bc"首先,将其重写为"%a'bc%"然后将其用作普通字符串参数.psycopg会将它重写为'%a \'bc%'.

如果q可能包含"%"并且您想要搜索它,那么请使用第二个.