python - UnicodeEncodeError : 'latin-1' codec can't encode character

标签 python mysql unicode pylons

当我尝试将外来字符插入数据库时​​,可能导致此错误的原因是什么?

>>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 of db.cursor().

关于python - UnicodeEncodeError : 'latin-1' codec can't encode character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3942888/

相关文章:

python - 关于获取数据的错误

python - 如何在 Julia 中使用 Python 函数?

php - 注册后重定向用户时出现问题

javascript - 在 JavaScript 中将 Windows-1252 十六进制值转换为 Unicode

Javascript,将unicode字符串转换为Javascript转义?

java - JspRuntimeLibrary : "this trick avoids escaping issues"

python - 为什么这里没有引发 StopIteration ?

python - 在第 n 次出现后删除字符串的其余部分

mysql - Tableau 中的联接会影响性能吗?

mysql - 当我在 jsp 中单击提交按钮时出现错误