Question:
When python2.7 queries or inserts Chinese data into mysql, Chinese garbled characters appear
---
Possible situations:
1. There is no encoding set for each item in the mysql database, the default is 'latin'
2. No default encoding is set when using MySQL.connect
3. The encoding of python is not set, python2.7 defaults to 'ascii'
4. No decoding
---
Solution:
1.Set the encoding of mysql
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 connection encoding parameters of MySQLdb in code
db=MySQLdb.connect(user='...',db='...',passwd='...',host='...',charset='utf8')<br />
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')
over