sqlite3.ProgrammingError:您不能使用8位字节串,除非您使用可以解释8位字节串的text_factory
在 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 库压缩时,我收到上述错误消息。我环顾四周,但找不到这个问题的简单答案。
Using SQLite3 in Python, I am trying to store a compressed version of a snippet of UTF-8 HTML code.
Code looks like this:
...
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)))
At which point at get the error:
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.
If I use 'text' rather than 'blob' and don't compress the HTML snippet, it works all fine (db is to large though). When I use 'blob' and compress via Python zlib library, I get the above error message. I looked around but couldn't find a simple answer for this one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果你想在sqlite3中使用8位字符串而不是unicode字符串,请为sqlite连接设置适当的text_factory:
If you want to use 8-bit strings instead of unicode string in sqlite3, set appropriate text_factory for sqlite connection:
找到了解决方案,我应该多花一点时间搜索。
解决方案是将值“转换”为 Python“缓冲区”,如下所示:
希望这对其他人有帮助。
Found the solution, I should have spent just a little more time searching.
Solution is to 'cast' the value as a Python 'buffer', like so:
Hopefully this will help somebody else.
为了使用 BLOB 类型,您必须首先将 zlib 压缩字符串转换为二进制数据 - 否则 sqlite 将尝试将其作为文本字符串处理。这是通过 sqlite3.Binary() 完成的。例如:
In order to work with the BLOB type, you must first convert your zlib compressed string into binary data - otherwise sqlite will try to process it as a text string. This is done with sqlite3.Binary(). For example:
语法:
5种可能的存储类型:NULL、INTEGER、TEXT、REAL和BLOB
BLOB一般用于存储pickled模型或dill pickled模型
Syntax:
5 types of possible storage: NULL, INTEGER, TEXT, REAL and BLOB
BLOB is generally used to store pickled models or dill pickled models
您可以使用 repr(html) 而不是原始输出来存储值,然后在检索要使用的值时使用 eval(html)。
You could store the value using repr(html) instead of the raw output and then use eval(html) when retrieving the value for use.