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]