# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   python_study
# FileName:      requests_method.py
# Author:       mwx
# Datetime:     2024/11/5 23:03
# Description:
# 
# ---------------------------------------------------------------------------
import pymysql

from Interface_automation.APIAutoText_v3_1_1 import log
from Interface_automation.APIAutoText_v3_1_1.commn.read_basic_ini import ReadBasicIni



class DB:
    def __init__(self):
        ini = ReadBasicIni()
        try:
            self.conn = pymysql.connect(
                                        host=ini.get_sql("host"),
                                        port=int(ini.get_sql("port")),
                                        user=ini.get_sql("user"),
                                        password=ini.get_sql("pwd"),
                                        database=ini.get_sql("database"),
                                        charset="utf8"
            )
            self.cursor = self.conn.cursor()
        except Exception as e:
            log.error(f"链接数据库错误，检查ini配置文件，错误描述为{e}")
            raise e
    def delete(self,sql):
        log.info(f"执行删除，传入的sql语句为{sql}")
        if isinstance(sql,str) and sql.strip().lower().startswith("delete"):
            print("xxx")
            try:
                self.cursor.execute(sql)
                self.conn.commit()
            except Exception as e:
                log.error(f"执行删除出错，传入的sql语句为{sql},错误类型为{type(e)},错误描述为{e}")
                raise e
        else:
            log.error(f"传入的sql语句错误，请检查sql语句，错误类型为ValueError")
            raise ValueError("传入的sql错误")

    def select(self,sql):
        log.info(f"执行查询的sql语句，传入的sql为{sql}")
        if isinstance(sql,str) and sql.strip().lower().startswith("select"):
            try:
                self.cursor.execute(sql)
            except Exception as e:
                log.error(f"执行查询出错，传入的sql为{sql},错误类型为{type(e)},错误描述为{e}")
                raise e
            else:
                result = self.cursor.fetchall()
                if result:
                    return result[0][0]
        else:
            log.error(f"传入的sql语句错误，传入的sql语句为{sql}，错误描述为ValueError")
            raise ValueError(f"传入的sql错误")




# if __name__ == '__main__':
#     s1 = 'DELETE FROM uc_demension WHERE CODE_="testAddDem";'
#     db = DB()
#     print(db.delete(s1))