最近在学习使用Python操作MySQL数据库,遇到了中文乱码问题。
一、MySQL数据库
- 库字符集参数:character set = utf8
- 表字符集参数:charset = utf8
- 列字符集参数:character set = utf8
二、Python文件
- 文件编码UTF-8
- 文件头添加#-*- encoding:utf-8 -*-
- 创建MySQL数据库连接时加上编码参数,如下例:
conn = MySQLdb.Connection(host='localhost', user='root', passwd='123456', db='test',charset='utf8') - 设置Python默认编码(非必须项)
reload(sys)
sys.setdefaultencoding('utf-8')
三、中文处理技巧(Unicode In Python, Completely Demystified)
- Decode early
- Unicode everywhere
- Encode late
四、更改mysql字符集:
- +--------------------------+---------------------------------+
- |
Variable_name | Value | - +--------------------------+---------------------------------+
- |
character_set_client | utf8 | - |
character_set_connection | utf8 | - |
character_set_database | utf8 | - |
character_set_filesystem | binary | - |
character_set_results | utf8 | - |
character_set_server | utf8 | - |
character_set_system | utf8 | - |
character_sets_dir | D:"mysql-5.0.37"share"charsets" | - +--------------------------+---------------------------------+
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
本文出自 “后街男孩” 博客,请务必保留此出处http://bsbforever.blog.51cto.com/1883792/1593682