python - pysqlite2 : ProgrammingError - You must not use 8-bit bytestrings

标签 python sqlite pysqlite

我目前出于自己的目的将文件名保存在 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/

相关文章:

python - 将海龟图形保存为 .eps 文件时,背景颜色显示在屏幕上但未保存在 .eps 文件中

python - 用于监控服务器的机器学习

java - SQLite - 在 Android 应用程序中加速 4,000 行插入

python - 警告 : IPython History requires SQLite, 您的历史将不会被保存

python - 为什么pip卸载不了pysqlite?

Python Pandas 多索引列 : Set first level of header column as index

python - 无法运行本地 Celery Worker,没有名为 myapp 的模块

sqlite - Play/滑动/SQLite演变不起作用

java - Android sqlite 将 WAL 文件内容刷新到主数据库文件中

python - Pysqlite 设置错误