扩展Python MySQLdb Cursor


Python shell下操作mysql一直使用MySqldb。
其默认的Cursor Class是使用tuple(元组)作为数据存储对象的,操作非常不便
1 p = 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)
#
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类:
 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 p = cursor.fetchone()
4 print(p.id, p.name)

相关内容

    暂无相关文章

评论关闭