# mysql数据库
import pymysql

from config import host, user, database_pwd, database, port


class DButils:
    __conn = None
    __cursor = None

    # 连接数据库
    @classmethod
    def get_conn(cls):
        if cls.__conn is None:
            cls.__conn = pymysql.connect(host=host, port=port, user=user, password=database_pwd, database=database,
                                         charset="utf8")
        return cls.__conn

    # 创建游标方法
    @classmethod
    def get_cursor(cls):
        if cls.__cursor is None:
            cls.__cursor = cls.get_conn().cursor()
        return cls.__cursor

    # sql执行查询方法
    @classmethod
    def select_sql(cls, sql):
        result = None
        try:
            cursor = cls.get_cursor()
            cursor.execute(sql)
            result = cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            cls.close_cursor()
            cls.close_conn()
            return result

    # 数据库的增删改操作
    @classmethod
    def uid_sql(cls, sql):
        try:
            conn = cls.get_conn()
            cursor = cls.get_cursor()
            cursor.execute(sql)
            conn.commit()
        except Exception as e:
            print(e)
            cls.get_conn().rollback()
        finally:
            cls.close_cursor()
            cls.close_conn()

    # 关闭游标方法
    @classmethod
    def close_cursor(cls):
        if cls.__cursor:
            cls.__cursor.close()
            cls.__cursor = None

    # 关闭连接
    @classmethod
    def close_conn(cls):
        if cls.__conn:
            cls.__conn.close()
            cls.__conn = None




