python - sqlite3.操作错误: Could not decode to UTF-8 column

标签 python sqlite

我有一个包含这行信息的 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()

最佳答案

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 - sqlite3.操作错误: Could not decode to UTF-8 column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751363/

相关文章:

sqlite 从事务到保存点的转换

php - PDO 将数据库类型更改为 SQLITE 会引发错误

sqlite - 多次关闭SQLite数据库是否安全?

python - PySpark:如何检查数据框中是否存在字符串值列表并将值打印到列表中

javascript - Django D3从mongodb读取csv数据来绘制图表

python - 如何从数据帧的子集中随机选择元素?

python - 半定规划中的绝对值和约束

python - Pandas 中的分组、加权、列平均值

sqlite - 如何显示zumero用户信息而不允许访问整个身份验证数据库?

c - sqlite3_*() 的正常例程是否有内存泄漏?