#-*- coding:utf8 -*- import MySQLdb import dbhash class DbManager(): dbConf = { 'host': 'localhost', 'user': '用户', 'password': '数据库密码', 'db_name': '数据库名称', 'port': 3306, 'charset': 'utf8', } def connect(self): #获取数据库连接 return MySQLdb.connect(self.dbConf['host'], user=self.dbConf['user'], passwd=self.dbConf['password'], db=self.dbConf['db_name'], charset=self.dbConf['charset']) def query(self, sql): connect = self.connect() cur = connect.cursor() cur.execute(sql) index = cur.description result = [] for res in cur.fetchall(): row = {} for i in range(len(index)-1): row[index[i][0]] = res[i] result.append(row) connect.close() return result def update(self, sql): connect = self.connect() cur = connect.cursor() result = cur.execute(sql) connect.commit() connect.close() return result def insert(self, sql): connect = self.connect() cur = connect.cursor() result = cur.execute(sql) connect.commit() connect.close() return result def delete(self, sql): connect = self.connect() cur = connect.cursor() result = cur.execute(sql) connect.commit() connect.close() return result def count(self, sql): connect = self.connect() cur = connect.cursor() result = cur.execute(sql) connect.close() return result
该组件主要是简单封装了数据查询的地功能,亮点是
query(self, sql)方法查询出来的数据都是以数据库字段名称为键名的字典的集合:
例:
sql = 'select id,userName,password from user limit 5; ';
res = DbManager().query(sql);
for r in res:
print r
结果:
{'userName': u'SuperAdmin', 'id': 1L}
{'userName': u'test', 'id': 2L}
{'userName': u'\u5f20\u5803', 'id': 3L}
{'userName': u'\u9648\u6d32\u9f99', 'id': 4L}
{'userName': u'ddd', 'id': 6L}
如果把print r 改成 print r['id'],输出结果将为: