【问题标题】:Python, mysqldb and unicodePython、mysqldb 和 unicode
【发布时间】:2011-11-10 19:15:33
【问题描述】:

我无法从 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

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

提前致谢,

西蒙

【问题讨论】:

    标签: python mysql unicode mysql-python


    【解决方案1】:

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

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

    【讨论】:

    • 我明白,事实是我认为可以要求 unicode 字符串而不是字节字符串。你知道use_unicode=True的作用是什么吗?
    • 它对我有理想的效果。我的列定义包含CHARACTER SET UTF8 而不是utf8_bin。 Afaik 这是唯一的区别。
    • @SimonRolin 问他的问题已经有一段时间了,但为了记录,MySQLdb.connect(use_unicode=True, charset='utf8', ...) 使 MySQL 返回 unicode。
    • 请注意,在 MySQLdb 1.2.3(在许多基于数据包的 Sitro 中仍然是当前版本)之前,存在一个阻止 utf8_bin 列正常工作的错误。在此处查看错误描述:sourceforge.net/p/mysql-python/bugs/289
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 2013-12-26
    相关资源
    最近更新 更多