python - sqlite3.ProgrammingError : You must not u

在 Python 中使用 SQLite3,我正在尝试存储 UTF-8 HTML 代码片段的压缩版本。

代码如下:

...
c = connection.cursor()
c.execute('create table blah (cid integer primary key,html blob)')
...
c.execute('insert or ignore into blah values (?, ?)',(cid, zlib.compress(html)))

在什么时候得到错误:

sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

如果我使用 'text' 而不是 'blob' 并且不压缩 HTML 片段,它可以正常工作(虽然 db 很大)。当我使用“blob”并通过 Python zlib 库进行压缩时,我收到上述错误消息。我环顾四周,但找不到一个简单的答案。

最佳答案

如果您想在 sqlite3 中使用 8 位字符串而不是 unicode 字符串,请为 sqlite 连接设置适当的 text_factory:

connection = sqlite3.connect(...)
connection.text_factory = str

关于python - sqlite3.ProgrammingError : You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3425320/

相关文章:

python - 如何从具有透明背景的 matplotlib 导出绘图?

python - 在系统范围内安装 pip 和 virtualenv 的官方 "preferred"

python - SQLAlchemy:如何过滤日期字段?

python - matplotlib 中的曲面图

python - 如何使用 Pandas 创建随机整数的 DataFrame?

python - 使用 pandas GroupBy.agg() 对同一列进行多个聚合

python - 如何在 Tesseract 和 OpenCV 之间进行选择?

python - Python 多处理模块的 .join() 方法到底在做什么?

python - 断言 numpy.array 相等性的最佳方法?

python - NumPy:同时 max() 和 min() 的函数