海上月明

          editer by sun
          posts - 162, comments - 51, trackbacks - 0, articles - 8
             :: 首頁 :: 新隨筆 ::  :: 聚合  :: 管理

          python操作sqlite3 碰到中文問題

          Posted on 2013-06-07 19:01 pts 閱讀(5844) 評論(0)  編輯  收藏 所屬分類: Python

          錯問癥狀:

          OperationalError: Could not decode to UTF-8 column 'shouji_lanshouyuan' with text '國際2部 鄔長春'

          解決方案:

          conn = sqlite3.connection(" ... ")
          conn.text_factory = str

          解決問題方案來源:http://bbs.csdn.net/topics/250055755

          設置python使用什么類型來處理sqlite3的text類型,默認是unicode,所以才會產生
          OperationalError: Could not decode to UTF-8 column 'name' with text '國內其他' 
          這個錯誤

          因為從數據庫中取出數據時,是gbk編碼(因為你上次存進去的是gbk)
          conn.text_factory的默認值是unicode,python會嘗試將text類型的字段轉換成unicode,就產生了錯誤

           

          附:sqlite3的row操作:

          Row對象的詳細介紹

          class sqlite3.Row

          Row instance serves as a highly optimized row_factory for Connection objects. It tries to mimic a tuple in most of its features.

          It supports mapping access by column name and index, iteration, representation, equality testing and len().

          If two Row objects have exactly the same columns and their members are equal, they compare equal.

          Changed in version 2.6: Added iteration and equality (hashability).

          keys()

          This method returns a tuple of column names. Immediately after a query, it is the first member of each tuple in Cursor.description.

          New in version 2.6.

              下面舉例說明

          復制代碼
          cx.row_factory = sqlite3.Row

          = cx.cursor()

          c.execute('select * from catalog')
           <sqlite3.Cursor object at 0x05666680>

          = c.fetchone()

          type(r)
          <type 'sqlite3.Row'>

          r
          <sqlite3.Row object at 0x05348980>

          print r
          (0, 
          10, u'\u9c7c', u'Yu')

          len(r)
          4

          r[2]            #使用索引查詢
          u'\u9c7c'

          r.keys()
          ['id''pid''name''nickname']

           使用列的關鍵詞查詢
          In [43]: r['id']
          Out[43]: 0
          In [44]: r['name']
          Out[44]: u'\u9c7c'

           

          主站蜘蛛池模板: 会泽县| 胶南市| 同心县| 绥芬河市| 龙海市| 天水市| 高州市| 晋宁县| 浦城县| 泸西县| 山西省| 秦皇岛市| 万年县| 怀集县| 沾益县| 凭祥市| 云梦县| 百色市| 上蔡县| 怀集县| 郧西县| 阜阳市| 岢岚县| 西昌市| 郎溪县| 宽城| 湘阴县| 尼勒克县| 惠来县| 沁源县| 津市市| 民乐县| 法库县| 淮北市| 柳州市| 云南省| 银川市| 洮南市| 阜南县| 嘉鱼县| 慈利县|