python - sqlite3.ProgrammingError : You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings

标签 python unicode sqlite zlib

在 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 - 如何在Python中迭代 `groupBy`返回的对象?

python - 将 unicode 元素读入 numpy 数组

javascript - PHP:如何使用unicode字符将文件写入磁盘

mysql - 如何在我的数据库中用 SPACE 替换 "+"(加号)?

android - android sqlite中的大量数据

iphone - 在 iPhone/iPod Touch 上本地存储包含 333,000 行的 sqlite 数据库是否可行?

python - 在 Keras 中使用 tf.metrics?

python - 在 sympy 中分解多边形

python - 这些模型是否等效?

javascript regex test() 无法识别丹麦语字符