Solve python2.7 query MySQL when the Chinese garbled _python

Source: Internet
Author: User

Problem:

python2.7 query or Insert Chinese data in MySQL when the Chinese garbled

---
Possible situations:

1.mysql database items are not set to encode, default is ' Latin '
2. No default encoding is set when using Mysql.connect
3. No Python encoding is set, python2.7 defaults to ' ASCII '
4. No decoding
---

Workaround:

1. Set the code for MySQL

Ubuntu executes the following statement:

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

and insert the statement inside:

[Client]
Default-character-set=utf8
[mysqld]
Character-set-server=utf8
collation-server=utf8_general_ci 

Quit Vim
Restart MySQL:

* * sudo service mysql restart * *

2. Set MYSQLDB Connection encoding parameters in code

db=MySQLdb.connect(user='...',db='...',passwd='...',host='...',charset='utf8')

3. Set the 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.