关于这个问题网上搜到的多数回答都是:
query = query.decode(errors=‘replace’)
修改成 query = query.encode(errors=‘replace’)
但是感觉这样修改看着就很奇怪,就去看了一下原函数:
def last_executed_query(self, cursor, sql, params):
# With MySQLdb, cursor objects have an (undocumented) "_executed"
# attribute where the exact query sent to the database is saved.
# See MySQLdb/cursors.py in the source distribution.
query = getattr(cursor, '_executed', None)
if query is not None:
query = query.decode(errors='replace')
return query
在 Python 中,有 2 种常用的字符串类型,分别为 str 和 bytes 类型,其中 str 用来表示 Unicode 字符,bytes 用来表示二进制数据。str 类型和 bytes 类型之间就需要使用 encode() 和 decode() 方法进行转换。
原函数如果类型不出错decode出来返回的都是str类型,如果像上面那么改不又变回字节流类型了吗,所以就斗胆给源码里面加了一行判断:
def last_executed_query(self, cursor, sql, params):
# With MySQLdb, cursor objects have an (undocumented) "_executed"
# attribute where the exact query sent to the database is saved.
# See MySQLdb/cursors.py in the source distribution.
query = getattr(cursor, '_executed', None)
if query is not None:
if isinstance(query, bytes):
query = query.decode(errors='replace')
return query
改完运行暂时没什么问题,不确定有没有其他影响。