# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   test66
# FileName:      db.py
# Author:       lao_zhao
# Datetime:     2025/5/9 11:34
# Description:
# 
# ---------------------------------------------------------------------------
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_msg("host"),
            port=int(ini.get_sql_connect_msg("port")),
            user=ini.get_sql_connect_msg("user"),
            password=ini.get_sql_connect_msg("password"),
            database=ini.get_sql_connect_msg("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.fetchone()
            if select_result:
                return select_result[0]
        else:
            raise ValueError("删除的sql语句错误")