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 步步為營

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

          主站蜘蛛池模板: 伊金霍洛旗| 天全县| 桂林市| 汉阴县| 日土县| 慈溪市| 都匀市| 乃东县| 晋城| 汝阳县| 阿克苏市| 镇巴县| 衡水市| 南陵县| 星子县| 清丰县| 舞阳县| 灌云县| 河东区| 微博| 璧山县| 定南县| 沧州市| 普安县| 化州市| 鄂托克旗| 九龙城区| 万宁市| 翁牛特旗| 道孚县| 常熟市| 来宾市| 文化| 通州市| 汝阳县| 肇庆市| 蓝山县| 喜德县| 岑巩县| 翁源县| 赤壁市|