当我尝试将外来字符插入数据库时,可能导致此错误的原因是什么?
>>UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in position 0: ordinal not in range(256)
我该如何解决?
谢谢!
最佳答案
我在使用 Python MySQLdb 模块时遇到了同样的问题。由于 MySQL 将允许您在文本字段中存储几乎任何您想要的二进制数据,而不管字符集如何,我在这里找到了我的解决方案:
Using UTF8 with Python MySQLdb
编辑:引用上述 URL 以满足第一条评论中的请求...
"UnicodeEncodeError:'latin-1' codec can't encode character ..."
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:
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 ofdb.cursor()
.
关于python - UnicodeEncodeError : 'latin-1' codec can't encode character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3942888/