欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python查詢mysql中文亂碼問題

 更新時(shí)間:2014年11月09日 11:34:01   投稿:hebedich  
本文主要是解決python2.7在查詢mysql時(shí)產(chǎn)生中文亂碼的處理方法,非常的有用,親測(cè)可行,推薦給大家

問題:

python2.7 查詢或者插入中文數(shù)據(jù)在mysql中的時(shí)候出現(xiàn)中文亂碼

---

可能情況:

1.mysql數(shù)據(jù)庫(kù)各項(xiàng)沒有設(shè)置編碼,默認(rèn)為'latin'

2.使用MySQL.connect的時(shí)候沒有設(shè)置默認(rèn)編碼

3.沒有設(shè)置python的編碼,python2.7默認(rèn)為'ascii'

4.沒有解碼

---

解決方法:

1.設(shè)置mysql的編碼

ubuntu執(zhí)行下列語(yǔ)句:
** sudo vim /etc/mysql/my.cnf **
然后在里面插入語(yǔ)句:

[client]
default-character-set=utf8
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
退出 vim
重新啟動(dòng)mysql:
** sudo service mysql restart **

2.在code中設(shè)置MySQLdb的連接編碼參數(shù)

db=MySQLdb.connect(user='...',db='...',passwd='...',host='...',charset='utf8')
3.在code中設(shè)置python默認(rèn)編碼

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

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

相關(guān)文章

最新評(píng)論