pysqlite2: 编程错误 - 不能使用8位字节字符串

13 投票
5 回答
16160 浏览
提问于 2025-04-15 22:43

我现在在用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(filename),来“切换我的应用程序使用Unicode字符串”时,又出现了这个错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 66: ordinal not in range(128)

有没有什么办法可以解决这个问题?我不想去修改我所有的文件来适应这个情况。

更新
如果我通过filename.decode("utf-8")来解码文本,还是会遇到上面的编程错误。

我的实际代码是这样的:

cursor.execute("select * from musiclibrary where absolutepath = ?;",
    [filename.decode("utf-8")])

那我的代码应该怎么写呢?

5 个回答

1

你有没有试过直接传递这个unicode字符串呢:

cursor.execute("select * from musiclibrary where absolutepath = ?;",(u'namé',))

你需要在脚本的开头添加文件编码:

# coding: utf-8
3

你应该把SQL语句的参数以Unicode格式传递。

这主要取决于你是怎么获取文件名列表的。也许你是通过 os.listdiros.walk 来读取文件系统?如果是这样,你可以通过给这两个函数传递一个Unicode参数,直接得到Unicode格式的文件名。
举个例子:

  • os.listdir(u'.')
  • os.walk(u'.')

当然,你可以把 u'.' 替换成你实际要读取的目录。只要确保它是一个Unicode字符串就可以了。

14

你需要指定filename的编码格式,以便将其转换为Unicode,比如说:filename.decode('utf-8')。如果你只是用unicode(...),它会使用控制台的编码格式,而这个编码通常不太可靠(而且很多时候是ascii)。

撰写回答