stone2083

          擴展Python MySQLdb Cursor

          Python shell下操作mysql一直使用MySqldb。
          其默認的Cursor Class是使用tuple(元組)作為數據存儲對象的,操作非常不便
          1 = cursor.fetchone()
          2 print(p[0], p[1])
          如果有十幾個字段,光是數數位數,就把我數暈了。

          當然,MySqldb Cursor Class本身就提供了擴展,我們可以切換成DictCurosor作為默認數據存儲對象,如
          MySQLdb.connect(host='127.0.0.1', user='sample', passwd='123456', db='sample', cursorclass=DictCursor, charset='utf8')
          #
          = cursor.fetchone()
          print(p['id'], p['name'])
          字典的方式優于元祖。

          但是,"[]"這個符號寫寫比較麻煩,并且我編碼風格帶有強烈的Java習慣,一直喜歡類似"p.id","p.name"的寫法。
          于是,擴展之
          1. 擴展Dict類,使其支持"."方式:
           1 class Dict(dict):
           2     
           3     def __getattr__(self, key):
           4         return self[key]
           5     
           6     def __setattr__(self, key, value):
           7         self[key] = value
           8     
           9     def __delattr__(self, key):
          10         del self[key]
          2. 擴展Curosor,使其取得的數據使用Dict類:
           1 class Cursor(CursorStoreResultMixIn, BaseCursor):
           2 
           3     _fetch_type = 1
           4 
           5     def fetchone(self):
           6         return Dict(CursorStoreResultMixIn.fetchone(self))
           7 
           8     def fetchmany(self, size=None):
           9         return (Dict(r) for r in CursorStoreResultMixIn.fetchmany(self, size))
          10 
          11     def fetchall(self):
          12         return (Dict(r) for r in CursorStoreResultMixIn.fetchall(self))

          這下,就符合我的習慣了:
          1 MySQLdb.connect(host='127.0.0.1', user='sample', passwd='123456', db='sample', cursorclass=Cursor, charset='utf8')
          2 #
          3 = cursor.fetchone()
          4 print(p.id, p.name)

          posted on 2011-06-18 00:41 stone2083 閱讀(2704) 評論(1)  編輯  收藏 所屬分類: python

          Feedback

          # re: 擴展Python MySQLdb Cursor 2011-06-18 09:30 步步為營

          不錯,學習了  回復  更多評論   

          主站蜘蛛池模板: 台北市| 新乡市| 石景山区| 贞丰县| 南郑县| 宜宾县| 新邵县| 山阳县| 凯里市| 辛集市| 巴中市| 延边| 贡山| 木里| 吴忠市| 普陀区| 邳州市| 金乡县| 宁陵县| 青田县| 安平县| 古交市| 达尔| 柞水县| 兴山县| 泽州县| 伽师县| 荔波县| 辽源市| 襄垣县| 襄城县| 南陵县| 石棉县| 神池县| 河池市| 玛纳斯县| 阳原县| 红安县| 仁布县| 彭水| 特克斯县|