Solve the problem of Chinese garbled characters when querying mysql in python2.7

WBOY
Release: 2016-12-05 13:27:18
Original
1570 people have browsed it

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 **
Copy after login

Then insert the statement inside:

[client]
default-character-set=utf8
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci 
Copy after login

Exit vim
Restart mysql:

** sudo service mysql restart **
Copy after login

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')
Copy after login

4. Remember to decode

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

over

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!