# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   test60
# FileName:      db.py
# Author:       lao_zhao
# Datetime:     2024/5/20 14:08
# Description:
# 
# ---------------------------------------------------------------------------
import pymysql

from InterfaceAutoTest import log_decorator
from InterfaceAutoTest.common.read_ini import ReadIni
from InterfaceAutoTest.data_config.settings import *


class DB:
    @log_decorator
    def __init__(self):
        """链接数据库，获取链接对象和游标对象"""
        ini = ReadIni()
        try:
            self.conn = pymysql.connect(
                host=ini.get_db_connect_message(HOST_KEY),
                port=int(ini.get_db_connect_message(PORT_KEY)),
                user=ini.get_db_connect_message(USERNAME_KEY),
                password=ini.get_db_connect_message(PASSWORD_KEY),
                database=ini.get_db_connect_message(DATABASE_KEY),
                charset="utf8"
            )
            self.cursor = self.conn.cursor()
        except Exception as e:
            raise e

    @log_decorator
    def close(self):
        """关闭吧数据库链接"""
        self.cursor.close()
        self.conn.close()

    @log_decorator
    def delete_func(self, sql):
        """执行删除的sql语句"""
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            raise e

    @log_decorator
    def select_func(self, sql):
        """执行查询的sql语句，并返回查询结果"""
        try:
          self.cursor.execute(sql)
        except Exception as e:
            raise e
        else:
            result_select = self.cursor.fetchall()
            if result_select:
                return result_select[0][0]


if __name__ == '__main__':
    db = DB()
