【问题标题】:sqlite3.OperationalError: Could not decode to UTF-8 columnsqlite3.OperationalError:无法解码为 UTF-8 列
【发布时间】:2023-03-10 21:07:01
【问题描述】:

我有一个带有这行信息的sqlite数据库,ù真的应该是'-'

sqlite> select * from t_question where rowid=193;
193|SAT1000|having a pointed, sharp qualityùoften used to describe smells|pungent|lethargic|enigmatic|resolute|grievous

当我从 python 读取该行时,我得到了这个错误,我做错了什么?

Traceback (most recent call last):
  File "foo_error.py", line 8, in <module>
    cur.execute(sql_string)
  sqlite3.OperationalError: Could not decode to UTF-8 column 'posit' with text 'having a pointed, sharp qualityùoften used to describe smells'

Python 文件:

import sqlite3
conn = sqlite3.connect('sat1000.db')
cur = conn.cursor()
sql_string = 'SELECT * FROM t_question WHERE rowid=193'
cur.execute(sql_string)
conn.close()

【问题讨论】:

    标签: python sqlite


    【解决方案1】:

    text_factory 设置为str

    conn = sqlite3.connect('sat1000.db')
    conn.text_factory = str
    

    这将cause cur to return strs 而不是自动尝试使用UTF-8 编解码器解码str

    我找不到任何可以将'ù' 转换为连字符的解码和编码链,但有许多可能的 unicode 连字符,例如u'-'u'\xad'u'\u2010'u'\u2011'u'\u2043'u'\ufe63'u'\uff0d',我不排除可能存在这样的解码/编码链。但是,除非您能找到正确的转换,否则最简单的方法可能是简单地使用 str.replace 来修复字符串。

    更正:

    In [43]: print('ù'.decode('utf-8').encode('cp437').decode('cp1252'))
    —    # EM DASH u'\u2014'
    

    因此存在可以将'ù' 转换为某种形式的连字符的解码/编码链。

    【讨论】:

    • 这在当前版本的 Python 3 中不起作用。有关另一种解决方案,请参阅下面的答案。
    【解决方案2】:

    conn.text_factory = str 不适合我。

    我使用conn.text_factory = bytes。参考这里:https://stackoverflow.com/a/23509002/6452438

    【讨论】:

      【解决方案3】:

      unutbu 的答案在当前版本的 Python 3 中不起作用。设置 conn.text_factory = str 不会做任何事情,因为默认值为 text_factory is already str

      问题可能是数据库列中的文本不是有效的 UTF-8。默认情况下,Python 的decode() 函数在看到这样的文本时会抛出异常。但是你可以设置一个text_factory 告诉decode() 忽略此类错误,如下所示:

      conn = sqlite3.connect('my-database.db')
      conn.text_factory = lambda b: b.decode(errors = 'ignore')
      

      那么查询应该运行没有错误。

      【讨论】:

        猜你喜欢
        • 2019-10-29
        • 1970-01-01
        • 2015-07-19
        • 2011-01-01
        • 2021-03-22
        • 1970-01-01
        • 2013-06-12
        • 2018-04-22
        • 1970-01-01
        相关资源
        最近更新 更多