海上月明

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

          python操作sqlite3 碰到中文問題

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

          錯(cuò)問癥狀:

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

          解決方案:

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

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

          設(shè)置python使用什么類型來處理sqlite3的text類型,默認(rèn)是unicode,所以才會(huì)產(chǎn)生
          OperationalError: Could not decode to UTF-8 column 'name' with text '國內(nèi)其他' 
          這個(gè)錯(cuò)誤

          因?yàn)閺臄?shù)據(jù)庫中取出數(shù)據(jù)時(shí),是gbk編碼(因?yàn)槟闵洗未孢M(jìn)去的是gbk)
          conn.text_factory的默認(rèn)值是unicode,python會(huì)嘗試將text類型的字段轉(zhuǎn)換成unicode,就產(chǎn)生了錯(cuò)誤

           

          附:sqlite3的row操作:

          Row對(duì)象的詳細(xì)介紹

          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.

              下面舉例說明

          復(fù)制代碼
          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']

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

           

          主站蜘蛛池模板: 额济纳旗| 北海市| 恭城| 佛坪县| 灵山县| 额敏县| 格尔木市| 旅游| 晋州市| 桑日县| 温泉县| 咸丰县| 桃江县| 桦甸市| 双柏县| 连城县| 革吉县| 隆化县| 米泉市| 乌海市| 上犹县| 儋州市| 阿克苏市| 项城市| 平阳县| 韶山市| 尼玛县| 霸州市| 吴桥县| 灵丘县| 维西| 新巴尔虎左旗| 双牌县| 汝南县| 磐安县| 河曲县| 论坛| 富平县| 福鼎市| 建湖县| 盐山县|