Python MySQL Chinese garbled

Source: Internet
Author: User

When saving Chinese characters to MySQL DATA in Python, Chinese characters in the Database become garbled characters. I guess it's about Chinese encoding.

MySQL uses UTF-8. I have converted the field into UTF-8. I found that it still does not work. TestCodeAs follows:

#! /Usr/bin/ENV Python
# Coding = UTF-8
Import OS
Import mysqldb

Conn = mysqldb. Connect (host = 'IP', user = 'user', passwd = '******')
Cursor = conn. cursor ()
Conn. select_db ('sample _ info ');
Value = [U "Chinese test". Decode ('utf8')]
Print Value
Cursor.exe cute ("insert into tttt (tttt) values (% s)", value)

Later, I checked the information on the Internet and found that the problem was caused by the connect () function. I found that the charset should be set to utf8.
That is:
#! /Usr/bin/Python
#-*-Coding: UTF-8 -*-
Import OS
Import mysqldb

Conn = mysqldb. Connect (host = 'IP', user = 'user', passwd = '******',Charset = 'utf8')
Cursor = conn. cursor ()
Conn. select_db ('sample _ info ');
Value = [U "Chinese test"]
Print Value
Cursor.exe cute ("insert into tttt (tttt) values (% s)", value)

see this document http://www.mikusa.com/python-mysql-docs/docs/MySQLdb.connections.html
[MySQL Python Learning Documentation http://www.mikusa.com/python-mysql-docs/index.html]

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.