When python2.7 queries mysql the Chinese garble appears

  • 2020-05-12 02:49:56
  • OfStack

Question:

When python 2.7 queries or inserts Chinese data in mysql, Chinese garbled characters appear

---
Possible situations:

1. No encoding is set for each item in mysql database, and the default is 'latin'.
2. No default encoding is set when MySQL.connect is used
3. python encoding is not set, python2.7 defaults to 'ascii'
4. No decoding
---

Solutions:

1. Set the encoding of mysql

ubuntu executes the following statements:


** sudo vim /etc/mysql/my.cnf **

Then insert the statement:


[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 parameter of MySQLdb 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')

Remember to decode


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

over


Related articles: