原网页见: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" is the result of MySQLdb.connect, and "dbc" is the result of db.cursor().db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')
“db”是建立的连接对象,dbc是连接的cursor对象。