Python mysqldb Chinese garbled

Source: Internet
Author: User

Python operation MySQL requires installation of Python-mysql
Can be searched from the Internet, and the same as the normal Python package installation

After installation, the module name is MYSQLDB, can be used in Windows and Linux environment, the test is very useful,
But also found the annoying mess problem, finally used a few ways, solved!

I have used the following measures to ensure that MySQL output is not mess:
1 python file Set encoding utf-8 (file front plus #encoding =utf-8)
2 MySQL Database charset=utf-8
3 python connection mysql is plus parameter Charset=utf8
4 Set Python's default encoding to Utf-8 (sys.setdefaultencoding (Utf-8)

mysql_test.py

#encoding =utf-8import sysimport mysqldbreload (SYS) sys.setdefaultencoding ('Utf-8') DB=mysqldb.connect (user='Root', charset='UTF8') cur=db.cursor () Cur.execute ('Use mydb') Cur.execute ('select * from MYTB limit') F=file ("/home/user/work/tem.txt",'W') forIinchCur.fetchall (): F.write (str (i)) F.write (" ") F.close () cur.close ()

The above is a script on Linux, Windows is working properly!

Note: The configuration file settings for MySQL must also be configured as UTF8

Set the MySQL my.cnf file, set the default character set (usually in/etc/mysql/my.cnf) in the [Client]/[mysqld] section:

[Client]
Default-character-set = UTF8
[Mysqld]
Default-character-set = UTF8

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.