PyMySQL SQL和结果 中文乱码问题 解决

一、执行带有中文的SQL,出现sql.encode(self.encoding, 'surrogateescape'),出现如下错误:

File "C:\Program Files\Python37\lib\site-packages\pymysql\connections.py", line 891, in query
    sql = sql.encode(self.encoding, 'surrogateescape')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 207-208: ordinal not in range(256)

解决办法为将:

cursors.execute(sql)

修改为:

cursors.execute(sql.encode('utf8'))

 二、SQL查询到的结果中出现中文乱码

出错的情况如下:

原因:忘记加“charset='utf8'”

pymysql.connect(host='192.168.3.95',
                     port=3306,
                     user='tester',
                     passwd='Aa123456',
                     database='db_cust',
                     #charset='utf8'
                     )

加上即可,修复后结果如下:

猜你喜欢

转载自blog.csdn.net/nixonwuying/article/details/87369558