# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   test65
# FileName:      db.py
# Author:       lao_zhao
# Datetime:     2025/3/12 14:10
# Description:
# 
# ---------------------------------------------------------------------------
from cmath import isnan
from lib2to3.fixes.fix_next import is_assign_target

import pymysql

from APIAutoTest_v3 import log_decorator
from APIAutoTest_v3.common.read_system_ini import ReadSystemIni


class DB:
    @log_decorator
    def __init__(self):
        """创建连接对象和游标对象"""
        ini = ReadSystemIni()
        self.conn = pymysql.connect(
            host=ini.get_sql_connect_mgs("host"),
            port=int(ini.get_sql_connect_mgs("port")),
            user=ini.get_sql_connect_mgs("user"),
            password=ini.get_sql_connect_mgs("password"),
            database=ini.get_sql_connect_mgs("database"),
            charset="utf8"
        )
        self.cursor = self.conn.cursor()

    @log_decorator
    def close(self):
        """关闭游标和连接对象"""
        self.cursor.close()
        self.conn.close()

    @log_decorator
    def delete(self, sql_sentence):
        """执行删除的sql语句"""
        if isinstance(sql_sentence, str) and sql_sentence.lower().startswith("delete"):
            self.cursor.execute(sql_sentence)
            self.conn.commit()
        else:
            raise ValueError("删除的sql语句错误")

    @log_decorator
    def select(self, sql_sentence):
        """执行查询的sql语句"""
        if isinstance(sql_sentence, str) and sql_sentence.lower().startswith("select"):
            self.cursor.execute(sql_sentence)
            select_result = self.cursor.fetchall()
            if select_result:
                return select_result[0][0]
        else:
            raise ValueError("删除的sql语句错误")