首页 > 代码库 > python mysql 查询返回字典结构

python mysql 查询返回字典结构

 

cur = self.conn.cursor(MySQLdb.cursors.DictCursor)加上MySQLdb.cursors.DictCursor可以返回字典结构

{列名:值}
class MYSQL():
    def __init__(self,host,user,pwd,db):
        self.host = host
        self.user = user
        self.pwd = pwd
        self.db = db
    def __GetConnect(self):
        """
        得到连接信息
        返回: conn.cursor()
        """
        if not self.db:
            raise(NameError,"没有设置数据库信息")
        self.conn = MySQLdb.connect(self.host,self.user,self.pwd,self.db,charset=utf8)
        cur = self.conn.cursor(MySQLdb.cursors.DictCursor)#返回字典结构
        if not cur:
            raise(NameError,"连接数据库失败")
        else:
            return cur
    def ExecQuery(self,sql):

        cur = self.__GetConnect()
        cur.execute(sql)
        resList = cur.fetchall()

        #查询完毕后必须关闭连接
        self.conn.close()
        return resList