我目前出于自己的目的将文件名保存在 sqlite 数据库中。每当我尝试插入具有特殊字符(如 é 等)的文件时,它都会抛出以下错误:
pysqlite2.dbapi2.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.
当我通过使用 unicode 方法包装发送到 pysqlite 的值来“将我的应用程序切换到 Unicode 字符串”时:unicode(filename)
,它会抛出此错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 66: ordinal not in range(128)
我可以做些什么来摆脱它吗?修改我的所有文件以符合要求不是一种选择。
更新
如果我通过 filename.decode("utf-8")
解码文本,我仍然会收到上面的 ProgrammingError。
我的实际代码是这样的:
cursor.execute("select * from musiclibrary where absolutepath = ?;",
[filename.decode("utf-8")])
我的代码应该是什么样的?
最佳答案
需要指定filename
的编码才能转换为Unicode,例如:filename.decode('utf-8')
。仅使用 unicode(...)
选择控制台编码,这通常是不可靠的(通常是 ascii
)。
关于python - pysqlite2 : ProgrammingError - You must not use 8-bit bytestrings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2838100/