sqlite3.OperationalError: Could not decode to UTF8 column XXX with text '***'

环境:python3.2 sqllite3
代码如下:
import sqlite3 as sql

conn = sql.connect(r'c:\setupinfidb.db', detect_types=sql.PARSE_COLNAMES)
c = conn.cursor()
c.execute('select * from setuplog')
for row in c:
 print(row)

运行以上代码时,提示:
Traceback (most recent call last):
  File "sqlitetest.py", line x, in <module>
    c.execute('select * from setuplog')
sqlite3.OperationalError: Could not decode to UTF-8 column 'logtype' with text '\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd'

这个意思是说column ‘logtype’ 不能通过UTF-8 decode,就是logtype不是用utf8编码的
一般情况下这个情况出现在text类型的数据上面
这个可以通过设置 conn.text_factory 解决
如 conn.text_factory = bytes
把text类型当bytes来解释,就不会出错了
不过,这样也不太好,如果知道是什么编码就好了,例子代码是gbk编码的
这里可以这样设置:
conn.text_factory = lambda x : str(x, 'gbk', 'ignore')
指示以gbk来解码而不是默认的utf8

原文地址:https://www.cnblogs.com/xkxjy/p/3672269.html