python2.7 query or Insert Chinese data in MySQL when there is a Chinese garbled
---
Possible conditions:
1.mysql database items are not set encoding, default to ' Latin '
2. The default encoding is not set when using Mysql.connect
3. Python encoding is not set, python2.7 defaults to ' ASCII '
4. No decoding
---
Workaround:
1. Set the MySQL encoding
Ubuntu executes the following statements:
* * sudo vim/etc/mysql/my.cnf * *
Then insert the statement inside:
[Client]
Default-character-set=utf8
[Mysqld]
Character-set-server=utf8
Collation-server=utf8_general_ci
Exit vim
Restart MySQL:
* * sudo service mysql restart * *
2. Set the MYSQLDB connection encoding parameter in code
Db=mysqldb.connect (user= ' ... ', db= ' ... ', passwd= ' ... ', host= ' ... ', charset= ' UTF8 ')
3. Set python default encoding in code
#-*-coding:utf-8-*-
Import Sys
Reload (SYS)
Sys.setdefaultencoding (' Utf-8 ')
4. Remember to decode
t = Cursor.fetchall ()
s = T[0][1].decode (' Utf-8 ')
Python query MySQL Chinese garbled problem