您的位置:首页 > 编程语言 > Python开发

Python, MySQLdb 编码问题 UnicodeEncodeError:'latin-1' codec can't encode character ...

2016-04-24 12:57 836 查看
原网页见:http://www.dasprids.de/blog/2007/12/17/python-mysqldb-and-utf-8

在用python的MySQLdb库插入数据时,出现了UnicodeEncodeError:'latin-1' codec can't encode character ...错误提示,网上搜索了下,在stackoverflow上发现了个解决办法,分享给大家,避免在这上面浪费太多时间。

This is because MySQLdb normally tries to encode everythin to latin-1. This can be fixed by executing the following commands right after you've etablished the connection:

错误原因是由于MySQLdb会把数据编码为latin-1,为了解决这一问题,可以在建立数据库连接之后写上以下代码:

db.set_character_set('utf8')

dbc.execute('SET NAMES utf8;')

dbc.execute('SET CHARACTER SET utf8;')

dbc.execute('SET character_set_connection=utf8;')

"db" is the result of MySQLdb.connect, and "dbc" is the result of db.cursor().

“db”是建立的连接对象,dbc是连接的cursor对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pyhton MySQLdb 编码