# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   test67
# FileName:      db.py
# Author:       lao_zhao
# Datetime:     2025/6/13 14:39
# Description:
# 
# ---------------------------------------------------------------------------
import pymysql

from APIAutoTest_v3 import log_decorator
from APIAutoTest_v3.utils.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_statement):
        """执行删除的sql语句"""
        if isinstance(sql_statement, str) and sql_statement.lower().startswith("delete"):
            self.cursor.execute(sql_statement)
            self.conn.commit()
        else:
            raise ValueError("sql语句错误")

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