Python queries mysql Chinese garbled code problem

  • 2020-04-02 14:19:14
  • OfStack

Question:

Python2.7 queries or inserts Chinese data in mysql with Chinese garbled

---

Possible situations:

1. Mysql database is not set to code, default is' Latin '

2. No default code is set when using mysql.connect

3. Python encoding is not set. Python 2.7 defaults to 'ASCII'

4. No decoding

---

Solutions:

1. Set the encoding of mysql

Ubuntu executes the following statements:
** sudo vim /etc/mysql.cnf **
Then insert a statement inside:

[client]
Default - character - set = utf8
[mysqld]
Character - set - server = utf8
Collation - server = utf8_general_ci
Exit the vim
Restart mysql:
** sudo service mysql restart **

2. Set the connection encoding parameters of MySQLdb in code

The db = MySQLdb. Connect (user = '... ', db = '... 'and passwd ='... ', the host = '... 'charset =' utf8)
3. Set the python default code in code

# - * - coding: utf-8 - * -
The import sys
Reload (sys)
Sys. Setdefaultencoding (' utf-8)
Remember to decode

T = cursor. Fetchall ()
S = t [0] [1]. The decode (' utf-8)


Related articles: