擴展Python MySQLdb Cursor
Python shell下操作mysql一直使用MySqldb。其默認的Cursor Class是使用tuple(元組)作為數據存儲對象的,操作非常不便
1 p = cursor.fetchone()
2 print(p[0], p[1])
如果有十幾個字段,光是數數位數,就把我數暈了。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')
#
p = cursor.fetchone()
print(p['id'], p['name'])
字典的方式優于元祖。#

p = 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類: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]
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))
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 p = cursor.fetchone()
4 print(p.id, p.name)
2 #

3 p = cursor.fetchone()
4 print(p.id, p.name)
posted on 2011-06-18 00:41 stone2083 閱讀(2704) 評論(1) 編輯 收藏 所屬分類: python