pysqlite2:ProgrammingError - 不得使用 8 位字节串 [英] pysqlite2: ProgrammingError - You must not use 8-bit bytestrings

查看:27
本文介绍了pysqlite2:ProgrammingError - 不得使用 8 位字节串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前出于自己的目的将文件名保存在 sqlite 数据库中.每当我尝试插入具有特殊字符(如 é 等)的文件时,它都会引发以下错误:

I'm currently persisting filenames in a sqlite database for my own purposes. Whenever I try to insert a file that has a special character (like é etc.), it throws the following error:

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 字符串"时,它会抛出此错误:

When I do "switch my application over to Unicode strings" by wrapping the value sent to pysqlite with the unicode method like: unicode(filename), it throws this error:

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

我能做些什么来摆脱这种情况吗?修改我的所有文件以符合要求不是一种选择.

Is there something I can do to get rid of this? Modifying all of my files to conform isn't an option.

更新如果我通过 filename.decode("utf-8") 解码文本,我仍然收到上面的 ProgrammingError.

UPDATE If I decode the text via filename.decode("utf-8"), I'm still getting the ProgrammingError above.

我的实际代码如下所示:

My actual code looks like this:

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

我的代码应该是什么样的?

What should my code here look like?

推荐答案

您需要指定filename的编码,以便转换为Unicode,例如:filename.decode('utf-8').仅使用 unicode(...) 选择控制台编码,这通常是不可靠的(通常是 ascii).

You need to specify the encoding of filename for conversion to Unicode, for example: filename.decode('utf-8'). Just using unicode(...) picks the console encoding, which is often unreliable (and often ascii).

这篇关于pysqlite2:ProgrammingError - 不得使用 8 位字节串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆