python获取数据库连接并返回字典类型

 

# coding=utf-8
# !/usr/local/bin/python3

"""

对pymssql的简单封装
Purpose: 测试 pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
使用该库时,需要在Sql Server conf Manager里面将TCP/IP协议开启
Created: 2017/08/21
# delete from xxx where yyy='xxx'

created by, date: Carol, 2018/03
updated by, date:

"""

import pymysql, pymssql


class MSSQL:
    """
    注意事项:
        使用pymssql进行中文操作时候可能会出现中文乱码,解决的方案是:
    文件头加上 #coding=utf8
    sql语句中有中文的时候进行encode
       insertSql = "insert into WeiBo([UserId],[WeiBoContent],[PublishDate]) values(1,'测试','2012/2/1')".encode("utf8")
     连接的时候加入charset设置信息
        pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
    """
    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 = pymssql.connect(host=self.host, user=self.user, password=self.pwd, database=self.db, charset="utf8")
        cur = self.conn.cursor()
        if not cur:
            raise (NameError, "连接数据库失败")
        else:
            return cur

    def ExecQuery(self, sql):
        """
        执行查询语句ExecQuery调用示例:返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段;以及一个list:元素的列名列表
        ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
        resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
        for (id, NickName) in resList:
            print(str(id), NickName)
        :param sql:
        :return:
        """
        cur = self.__GetConnect()
        cur.execute(sql)
        resList = cur.fetchall()
        desc_res = cur.description
        # 查询完毕后必须关闭连接
        cur.close()
        self.conn.close()
        return resList, desc_res

    def ExecNonQuery(self, sql):
        """
        :param sql:
        :return:
        执行非查询语句ExecNonQuery调用示例:ms.ExecNonQuery("insert into WeiBoUser values('2','3')")
        """
        cur = self.__GetConnect()
        cur.execute(sql)
        self.conn.commit()
        cur.close()
        self.conn.close()


class MySQL:
    """
    mysql连接,执行sql,获取数据库数据
    """

    def __init__(self, host, user, pwd, db):
        self.host = host
        self.user = user
        self.pwd = pwd
        self.db = db

    def __get_connect(self):
        # 得到连接信息,返回: conn.cursor()
        if not self.db:
            raise (NameError, "没有设置数据库信息")
        # 打开数据库连接
        self.conn = pymysql.connect(host=self.host, user=self.user, password=self.pwd, database=self.db,
                                    charset="utf8")
        # 使用 cursor() 方法创建一个游标对象 cursor
        cur = self.conn.cursor()
        if not cur:
            raise (NameError, "连接数据库失败")
        else:
            return cur

    def execute_sql_query(self, sql):
        """
        执行查询语句execute_sql_query调用示例:返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段;以及一个list:元素的列名列表
        ms = pymysql(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
        resList = ms.execute_sql_query("SELECT id,NickName FROM WeiBoUser")
        for (id, NickName) in resList:
            print(str(id), NickName)
        :param sql:
        :return: 查询结果
        """
        cur = self.__get_connect()
        try:
            cur.execute(sql)
            resList = cur.fetchall()
            desc_res = cur.description
            return resList, desc_res
        except:
            print("Failed| execute mysql query failed.")
        finally:
            # 查询完毕后必须关闭连接
            cur.close()
            self.conn.close()

    def execute_sql_operate(self, sql):
        """
        :param sql:
        执行非查询语句execute_sql_operate调用示例:ms.execute_sql_operate("insert into WeiBoUser values('2','3')")
        """
        cur = self.__get_connect()
        try:
            cur.execute(sql)
            self.conn.commit()
        except:
            # 发生错误时回滚
            self.conn.rollback()
            print("Failed| execute mysql update/insert/delete failed.")
        finally:
            cur.close()
            self.conn.close()




# ----------------------------------------------------------------------------------------------
#  查询数据库并返回字典类型的字段名,相应字段值:
# sqlquery = "select * from user_info where user_name='test1'"
# ----------------------------------------------------------------------------------------------
def get_dict_value_from_db(sqlquery, flag='MSSQL'):
    try:
        res_dict = {}
        flag = flag.upper().strip()
        if flag == 'MSSQL':
            ms = MSSQL(host=db_host, user=db_user, pwd=db_pwd, db=db_name)
            resList = ms.ExecQuery(sqlquery)
            
        elif flag == 'MYSQL':
            ms = MySQL(db_host, db_user, db_pwd, db_name)
            resList = ms.execute_sql_query(sqlquery)
           
        else:
            resList = ''
            print('Fail| get_dict_value_from_db:' + str(sqlquery) + ' Failed.')
        row_list = resList[0]
        col_list = resList[1]
        cols = [d[0] for d in col_list]
        for row in row_list:
            res_dict = dict(zip(cols, row))  # 将两个列表合并成一个字典 dict(zip())方法
        return res_dict
    except Exception as e:
        raise Exception(f'Fail| get_dict_value_from_db failed.Unexpected error: {e}')

if __name__ == '__main__':
    sql_query = "select * from user_info where user_name='test1'"
    print(str(get_dict_value_from_db(sql_query)))

 

你可能感兴趣的:(Python,编程)