Home > Backend Development > Python Tutorial > python查询mysql中文乱码问题

python查询mysql中文乱码问题

WBOY
Release: 2016-06-10 15:19:05
Original
1397 people have browsed it

问题:

python2.7 查询或者插入中文数据在mysql中的时候出现中文乱码

---

可能情况:

1.mysql数据库各项没有设置编码,默认为'latin'

2.使用MySQL.connect的时候没有设置默认编码

3.没有设置python的编码,python2.7默认为'ascii'

4.没有解码

---

解决方法:

1.设置mysql的编码

ubuntu执行下列语句:
** sudo vim /etc/mysql/my.cnf **
然后在里面插入语句:

[client]
default-character-set=utf8
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
退出 vim
重新启动mysql:
** sudo service mysql restart **

2.在code中设置MySQLdb的连接编码参数

db=MySQLdb.connect(user='...',db='...',passwd='...',host='...',charset='utf8')
3.在code中设置python默认编码

# -*-coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
4.记得要解码

t = cursor.fetchall()
s = t[0][1].decode('utf-8')

Related labels:
source:php.cn
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