【问题标题】:MySQLdb execute() works with unicode but not with subclass of unicodeMySQLdb execute() 适用于 unicode,但不适用于 unicode 的子类
【发布时间】:2017-03-12 02:35:57
【问题描述】:

我正在构建一个使用其他方法扩展 unicode 类的库,我发现 MySQLdb 在使用我的 unicode 类时失败了。

这行得通:

In [23]: c.execute("""SELECT * FROM django_site WHERE domain LIKE %s""",(u'éric',))
Out[23]: 0L

但这不是:

In [24]: class UnicodeExtended(unicode):
    ...:     pass
    ...: 

In [25]: c.execute("""SELECT * FROM django_site WHERE domain LIKE %s""",(UnicodeExtended(u'éric'),))
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-25-9145669d2b00> in <module>()
----> 1 c.execute("""SELECT * FROM django_site WHERE domain LIKE %s""",(UnicodeExtended(u'éric'),))

/usr/lib/python2.7/dist-packages/MySQLdb/cursors.pyc in execute(self, query, args)
    205                 args = dict((key, db.literal(item)) for key, item in args.items())
    206             else:
--> 207                 args = tuple(map(db.literal, args))
    208             if not PY2 and isinstance(query, bytes):
    209                 query = query.decode(db.unicode_literal.charset)

/usr/lib/python2.7/dist-packages/MySQLdb/connections.pyc in literal(self, o)
    302 
    303         """
--> 304         s = self.escape(o, self.encoders)
    305         # Python 3 doesn't support % operation for bytes object.
    306         # We should decode it before using %.

/usr/lib/python2.7/dist-packages/MySQLdb/connections.pyc in string_literal(obj, dummy)
    213             # Note: string_literal() is called for bytes object on Python 3.
    214             def string_literal(obj, dummy=None):
--> 215                 return db.string_literal(obj)
    216             return string_literal
    217 

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)

是否可以以任何方式在 sql 查询参数中使用 unicode 的子类?

我的 UnicodeExtended 类中可能缺少一些东西...知道吗?

我正在使用 Python 2.7 和 MySQLdb 1.3.7

【问题讨论】:

    标签: python django unicode mysql-python


    【解决方案1】:

    我发现 MySQLdb 是直接测试 UnicodeType,它不支持 unicode 子类化。默认情况下,MySQLdb 将对无法识别的对象类型执行 str()。所以诀窍是添加 __str_ 方法:

    class UnicodeExtended(unicode):
        def __str__(self):
            return self.encode('utf-8')
    

    这是有效的。这也避免了 django 在使用 UnicodeExtended 对象时出现“_last_executed”错误。

    【讨论】:

      猜你喜欢
      • 2019-12-23
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多