我有一个用于执行查询的python MySQLdb包装器。每当我使用这个包装器在字符串字段中执行包含'%'符号的查询时,我得到一个TypeError。
class DataBaseConnection:
def __init__(self,dbName='default'
):
#set
dbDtls={}
dbDtls=settings.DATABASES[dbName]
self.__host=dbDtls['HOST']
self.__user=dbDtls['USER']
self.__passwd=dbDtls['PASSWORD']
self.__db=dbDtls['NAME']
self.dbName=dbName
def executeQuery(self, sqlQuery, criteria=1):
""" This method is used to Execute the Query and return the result back """
resultset = None
try :
cursor = connections[self.dbName].cursor()
cursor.execute(sqlQuery)
if criteria == 1:
resultset = cursor.fetchall()
elif criteria == 2:
resultset = cursor.fetchone()
transaction.commit_unless_managed(using=self.dbName)
#cursor.execute("COMMIT;")
#objCnn.commit()
cursor.close()
#objCnn.close()
except Exception,e:
resultset = False
objUtil=Utility()
error=''
error=str(e)+"\nSQL:"+sqlQuery
print error
objUtil.WriteLog(error)
del objUtil
return resultset
sql = """SELECT str_value FROM tbl_lookup WHERE str_key='%'"""
objDataBaseConnection = DataBaseConnection()
res = objDataBaseConnection.executeQuery(sql)
print res
我尝试转义'%'字符,但没有用。数据库字段是VARCHAR字段。
答案 0 :(得分:1)
您必须将所有要传递给MySQL的%符号转义为%%。原因是百分号用于表示要插入字符串的位置。所以,你可以这样做:
...execute("""SELECT id FROM table WHERE name = '%s'""", name)
并且存储在变量名中的值将被转义并插入到查询中。
答案 1 :(得分:1)
execute("""SELECT id FROM table WHERE name = '%s'""", (name));