python 数据库中文乱码

本文实例展示了一个脚本python用来转化表配置数据xml并生成相应的解析代码。
但是在中文编码上出现了乱码,现将解决方法分享出来供大家参考。
具体方法如下:

  1. Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
  2. MySQL数据库charset=utf-8
  3. Python连接MySQL是加上参数 charset=utf8
  4. 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)
    示例代码如下:
    复制代码 代码如下:

encoding=utf-8

import sys
import MySQLdb as mdb

reload(sys)
sys.setdefaultencoding('utf-8')

con = None

try:
con = mdb.Connect('localhost','root','jobin','zmld',charset='utf8')
cur = con.cursor()
cur.execute("show full columns from player")

numRows = int(cur.rowcount)

for i in range(numRows):
    row = cur.fetchone()
    comment = row[len(row) - 1]
    print comment

finally:
if con:
con.close()

原文地址:https://www.cnblogs.com/shamojituan/p/7039383.html