Python MySQLdb TypeError在查询中使用“%”

2024-09-30 01:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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字段。你知道吗


Tags: theselfexecutereturndeferrorcursordbname
2条回答

必须将所有要作为%%传递给MySQL的%符号转义。原因是百分号用于表示要插入字符串的位置。所以,你可以这样做:

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

变量名中存储的值将被转义并插入到查询中。你知道吗

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

相关问题 更多 >

    热门问题