# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   test59
# FileName:      db.py
# Author:       laozhao
# Datetime:     2024/3/18 15:27
# Description:
# 
# ---------------------------------------------------------------------------
import pymysql

from InterfaceAutoTest import log_decorator
from InterfaceAutoTest.common.read_ini import ReadIni


class DB:
    @log_decorator
    def __init__(self):
        """链接是数据库，获取链接对象和游标对象"""
        read_ini = ReadIni()
        try:
            self.conn = pymysql.Connect(
                host=read_ini.get_sql_connect_msg("host"),
                port=int(read_ini.get_sql_connect_msg("port")),
                user=read_ini.get_sql_connect_msg("user"),
                password=read_ini.get_sql_connect_msg("password"),
                database=read_ini.get_sql_connect_msg("database"),
                charset="utf8"
            )
            self.cursor = self.conn.cursor()
        except:
            raise ConnectionError("链接数据库失败")

    @log_decorator
    def close(self):
        self.cursor.close()
        self.conn.close()

    @log_decorator
    def delete(self, sql_sentence):
        """使用游标对象执行删除的sql语句"""
        try:
            self.cursor.execute(sql_sentence)
        except:
            raise ValueError("sql语句错误")
        else:
            self.conn.commit()

    @log_decorator
    def select(self, sql_sentence):
        """使用游标对象执行查询的sql语句，并返回查询的结果"""
        try:
            self.cursor.execute(sql_sentence)
        except:
            raise ValueError("sql语句错误")
        else:
            select_result = self.cursor.fetchall()
            if select_result:
                return select_result[0][0]
