1. 程式人生 > 其它 >python3 sqlite3 Could not decode to UTF-8 column 'name' with

python3 sqlite3 Could not decode to UTF-8 column 'name' with

這一般出現在不同編碼的資料獲取上, 比如Linux獲取Windows的資料,我遇到的都是UTF8的環境獲取GBK的文字

網上許多資料讓這麼做:

self.connector = sqlite3.connect(DBFilePath)
self.connector.text_factory = str
self.cursor = self.connector.cursor()

這樣還是會報錯,報錯內容一樣,仍然是什麼編碼無法解碼某某位置的字元啥的

其實

connector.text_factory = str

做了一件事,就是給connector賦值了一個函式,用來處理獲取的文字,定義為str,那麼拿到的文字就是 return str(text)

這裡我拿到的是GBK的漢字,直接str肯定還是報錯的,所以解決辦法就是從根本上解決,重新定義處理文字的函式

self.connector = sqlite3.connect(DBFilePath)
self.connector.text_factory = lambda x: x.decode("gbk")
self.cursor = self.connector.cursor()

這樣,cursor拿到原始資料轉換text的時候,就會return text.decode("gbk")

因為我知道原來的text是GBK編碼的,所以這裡可以自定義對應的解碼方式