原网页见: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对象。

本文介绍了一种解决使用Python的MySQLdb库时遇到的UnicodeEncodeError的方法。该错误通常发生在尝试将UTF-8编码的数据插入数据库时。解决步骤包括设置数据库连接的字符集为UTF-8。
948

被折叠的 条评论
为什么被折叠?



