Last active
August 29, 2015 14:05
-
-
Save shuxiang/9957663a17395c00c966 to your computer and use it in GitHub Desktop.
Revisions
-
shuxiang revised this gist
Aug 12, 2014 . 1 changed file with 7 additions and 7 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -49,10 +49,10 @@ def close(self): self.conn.close() def dictfetchall(cursor): "Returns all rows from a cursor as a dict" desc = cursor.description return [ Row(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] -
shuxiang created this gist
Aug 12, 2014 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,58 @@ import MySQLdb class Row(dict): """A dict that allows for object-like property access syntax.""" def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) class Gdbm(object): """通用数据库连接管理 general database mananger""" def __init__(self, host, user, passwd, db, charset="utf8"): self.host = host self.user = user self.passwd = passwd self.db = db self.conn = MySQLdb.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.db,charset=charset) self.cursor = self.conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) def query(self, sql): self.cursor.execute(sql) data = self.cursor.fetchall() return [Row(d) if type(d) is dict else d for d in data] def execute(self, sql): self.cursor.execute(sql) pk = self.conn.insert_id() self.conn.commit() return pk def execute_no_commit(self, sql): """execute many sql then commit by hand""" self.cursor.execute(sql) def query_as_dict(self, sql): """result is [dict{},...]""" self.cursor.execute(sql) return dictfetchall(self.cursor) def commit(self): self.conn.commit() def rollback(self): self.conn.rollback() def close(self): self.cursor.close() self.conn.close() def dictfetchall(cursor): "Returns all rows from a cursor as a dict" desc = cursor.description return [ Row(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ]