Python、mysqldb 和 unicode

标签 python mysql unicode mysql-python

我无法从 mysql 查询中获取 unicode 值。

这是我现在的做法:

>>> from MySQLdb import connect
>>> from MySQLdb.cursors import DictCursor
>>> con = connect(
    passwd = "****",
    db = 'my_db',
    user = "db_user",
    host = "localhost",
    cursorclass = DictCursor,
    use_unicode=True,
    charset="utf8"
)
>>> cursor = con.cursor ()
>>> cursor.execute (u'Select * from basic_applet')
>>> res = cursor.fetchall()
>>> print(res)
({'Title_de': 'test title', .... })
>>> type(res[0]['Title_de'])
<type 'str'>

如您所见,它没有返回 unicode。

在我的表结构中,Title_de 设置为 unicode。

IDbasic_applet  int(10)...
Title_de    varchar(75)     utf8_bin

我真的不知道我做错了什么,非常欢迎任何帮助。

提前致谢

西蒙

最佳答案

你得到的是一个字节串。您必须对其进行解码才能获得 unicode 字符串。基本上可以归结为:

>>> byte_string = 'F\xe9vrier'
>>> byte_string.decode('UTF-8')
u'Février'

关于Python、mysqldb 和 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7311397/

相关文章:

python - 如何为 ipython 创建项目特定的启动脚本

python - 如何并行化计算?

mysql - 它运行的 sql 查询会根据用户数量重复相同的结果

mysql - 强制使用多个索引 - mysql

python - 使用控制台让 python 在 Windows XP 上以 UTF8 打印

c++ - 使用 MinGW 的 c++ unicode 程序中的错误

python - 我在哪里可以将 `reverse=true` 倒序排列?

python - django RequestFactory 丢失 url kwargs

php - Codeigniter MySQL 安全性、htmlspecialcharacters 和 mysql_real_escape_string?

c++ - 无法使用 UNICODE 读取文件(存在)