我很难从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

我真的不知道我在做什么错,任何帮助真的会受到欢迎。

提前致谢,

西蒙

有帮助吗?

解决方案

您得到的是一个bytestring。您必须将其解码才能获得Unicode字符串。基本上归结为:

>>> byte_string = 'F\xe9vrier'
>>> byte_string.decode('UTF-8')
u'Février'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top