Home > Backend Development > Python Tutorial > python操作mysql中文显示乱码的解决方法

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-16 08:41:12
Original
1013 people have browsed it

本文实例展示了一个脚本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程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template