Heim >Backend-Entwicklung >Python-Tutorial >python操作mysql中文显示乱码的解决方法

python操作mysql中文显示乱码的解决方法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-16 08:41:12996Durchsuche

本文实例展示了一个脚本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()

希望本文所述对大家的Python程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn