在 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/