Search code examples
pythonmysqlspecial-charactersmysql-python

Python MySQLdb - TypeError with using '%' in queries


I have a python MySQLdb wrapper for executing the query. Whenever I execute a query containing a '%' symbol in a string field using this wrapper, I get a 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

I tried escaping the '%' character but didn't work. The database field is VARCHAR field.


Solution

  • You must escape all the % signs you want to be passed to MySQL as %%. The reason is that percent signs are used to denote places where you want to insert a string. So, you can do something like:

    ...execute("""SELECT id FROM table WHERE name = '%s'""", name)
    

    and the value stored in the variable name would be escaped and inserted into the query.