UnicodeEncodeError: 'latin-1' codec can't encode characters in position: ordinal not in range 256

0. 现象

python 使用MySQLdb写数据报错字符无法编码

UnicodeEncodeError: 'latin-1' codec can't encode characters in position: ordinal not in range 256

1. 原因

python 连接mysql时没有指定客户端编码,默认使用的latin字符集。utf-8中文正常显示,必须三端一致:分别是客户端,连接和mysql服务统一为utf8

2. 解决办法

conn.set_character_set('utf8')
dbc = conn.cursor()
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')

你可能感兴趣的:(Python,python,mysql,utf8)