2010-05-14 39 views
13

我目前在一個sqlite數據庫中爲我自己的目的持久化文件名。每當我嘗試插入具有特殊字符(如電子等)的文件,它引發以下錯誤:pysqlite2:ProgrammingError - 你不能使用8位字節

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字符串」與像unicode的方法pysqlite:unicode(filename),它拋出這個錯誤:

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

有什麼我可以做,以擺脫這種?修改我的所有文件以符合不是一個選項。

UPDATE 如果我通過filename.decode("utf-8")解碼文本,我仍然得到上面的ProgrammingError。

我的實際代碼如下所示:

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

我應該在這裏我的代碼樣子的?

+0

看起來像這樣的代碼,在你更新問題之後,實際上並不是產生錯誤的代碼,對吧? – metamatt 2011-01-11 05:23:48

+0

對,後來在應用程序中使用了類似的代碼。 – 2011-01-12 16:13:38

回答

14

您需要指定編碼filename以轉換爲Unicode,例如:filename.decode('utf-8')。只使用unicode(...)選擇控制檯編碼,這通常是不可靠的(通常是ascii)。

+0

我試過這樣做,但似乎我仍然得到上面提到的錯誤。我用我現在正在做的事更新了這篇文章,所以你可以看到我在做什麼。謝謝! – 2010-05-14 23:23:17

+0

我的不好,我有一些更糟糕的轉換髮生在我的腳本後來拋出相同的錯誤:) – 2010-05-15 00:53:43

1

你有沒有試圖通過直接的unicode字符串:

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

你需要在腳本的開頭添加文件編碼:

# coding: utf-8 
+0

如果我嘗試,它似乎工作。我遍歷大約3000個文件,並且它失敗的文件名如:02 - 鄰居#2(Laïka).mp3。有沒有一種轉換技術可以讓我在某處失蹤? – 2010-05-15 00:44:32

3

你應該通過爲Unicode參數你的SQL語句。

現在,這一切都取決於如何獲得文件名列表。也許你正在使用os.listdiros.walk來閱讀文件系統?如果是這樣的情況下,存在一種方法,有直接在文件名爲Unicode只是通過使一個Unicode參數任一這些功能:
實例:

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

當然,您可以將u'.'目錄替換爲您正在閱讀其內容的實際目錄。只要確保它是一個Unicode字符串。

1

你已經想通了這一點,但是:

我不認爲你實際上可以得到從cursor.execute ProgrammingError異常( 「從musiclibrary選擇*其中absolutepath =;?」[filename.decode( 「utf-8」)]),正如現在的問題所述。

utf-8解碼會爆炸,或者cursor.execute調用會對結果感到滿意。

-1

嘗試改變這一點:

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

在你的文件名由來不utf8編碼,改變utf8你的編碼。

相關問題