Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pysqlite2:编程错误-不能使用8位ByTestRing_Python_Sqlite_Pysqlite - Fatal编程技术网

Python pysqlite2:编程错误-不能使用8位ByTestRing

Python pysqlite2:编程错误-不能使用8位ByTestRing,python,sqlite,pysqlite,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

我目前正在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方法(如:unicodeDefileName)包装发送到pysqlite的值,将应用程序切换到Unicode字符串时,它会抛出以下错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 66: ordinal not in range(128)
我能做些什么来摆脱这个吗?修改我的所有文件以符合要求不是一个选项

更新 如果我通过filename.decodeutf-8解码文本,我仍然会收到上面的编程错误

我的实际代码如下所示:

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

这里的代码应该是什么样子?

您需要指定文件名的编码以转换为Unicode,例如:filename.decode'utf-8'。只是使用unicode。。。选择控制台编码,该编码通常不可靠且通常为ascii。

是否尝试直接传递unicode字符串:

cursor.execute("select * from musiclibrary where absolutepath = ?;",(u'namé',))
您需要在脚本开头添加文件编码:

# coding: utf-8

您应该将SQL语句的参数作为Unicode传递

现在,这完全取决于如何获得文件名列表。也许您正在使用os.listdir或os.walk读取文件系统?如果是这种情况,有一种方法可以直接将文件名作为Unicode,只需将Unicode参数传递给以下函数之一: 示例:

os.listdiru'' “沃库”
当然,您可以用正在读取其内容的实际目录替换u'.'目录。只需确保它是Unicode字符串。

您已经解决了这个问题,但是:

我认为您实际上无法从musiclibrary的cursor.executeselect*中获得编程错误异常,其中absolutepath=?;,[filename.decodeutf-8],如问题当前所述

utf-8解码将爆炸,或者cursor.execute调用将对结果感到满意。

尝试更改为:

cursor.execute("select * from musiclibrary where absolutepath = ?;",
    [unicode(filename,'utf8')])

在文件名源代码中,不要使用utf8编码,请将utf8更改为您的编码。

我尝试过这样做,但似乎仍然会遇到上述错误。我用我现在所做的更新了帖子,所以你可以看到我在做什么。谢谢糟糕的是,后来在我的脚本中发生了一些更糟糕的转换,并抛出了相同的错误:如果我尝试了,它似乎可以工作。我迭代了大约3000个文件,但在诸如:02-Neighborhood 2 Laïka.mp3这样的文件名上失败了。是否有一种转换技术我在某个地方遗漏了?看起来这段代码,在你更新了问题之后,实际上不是代码产生了错误,对吗?对,它在应用程序的后面是类似的代码。