Python MySQLdb - 在查询中使用 '%' 的类型错误

标签 python mysql special-characters mysql-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 字段。

最佳答案

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

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

存储在变量名中的值将被转义并插入到查询中。

关于Python MySQLdb - 在查询中使用 '%' 的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505959/

相关文章:

python - 数据存储区中的 Google App Engine 版本控制

PHP sql 语句 where 子句到多个数组值

javascript - 包含与号 (&) 字符的文件路径

python - 将 python 脚本的输出获取到 Jenkinsfile 中的变量中

python - DeleteView 有 2 个争论帖子和用户

python - keras LSTM 获取隐藏状态(将句子序列转换为文档上下文向量)

php - pdo,将 php 对象插入数据库

mysql - 使用 Spring Batch 作为 ETL 时如何进行审计

c - 在 C 中使用 "\n"和 "\0"以外的特殊字符

python - 下载以特殊字符命名的在线 PDF 文件