python查詢mysql中文亂碼問題_python

來源:互聯網
上載者:User

問題:

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')

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.