# -*- coding: utf-8 -*-
# 数据库连接类
# 作者: 陈磊
# 时间: 2019-10-21

from WorkUtils.UtilsLog import UtilsLog
from sqlalchemy.exc import ProgrammingError, OperationalError
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker


class UtilsDataBase:
    def __init__(self):
        self.log = UtilsLog()
        self.log.info("调用基础数据库连接类")
        self.log.info(self.__class__)
        self.errors = ProgrammingError, OperationalError, MultipleResultsFound, NoResultFound, AttributeError

        self.param = {}

    def conn_mysql(self, db_url, db_port, db_base, db_user, db_pw):
        """
        mysql数据库连接方法
        :param db_url: 数据库地址
        :param db_port: 数据库端口
        :param db_base: 数据库库名
        :param db_user: 数据库登录用户名
        :param db_pw: 数据库登录密码
        :return:
        """
        try:
            db = "mysql://%s:%s@%s:%s/%s?charset=utf8" % (db_user, db_pw, db_url, db_port, db_base)
            engine = create_engine(db, encoding="utf-8")
            # echo=True,

            db_session = sessionmaker(bind=engine)
            session = db_session()
            self.log.debug("数据库请求地址:")
            self.log.debug(db)
            self.log.debug(db_session)
            self.log.debug(session)
            return session
        except self.errors as e:
            self.log.error("异常:")
            self.log.error(e)

    def add_param(self, _key, value):
        if value is None:
            pass
        else:
            self.param[_key] = value
