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)))

좋은 웹페이지 즐겨찾기