# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   PythonProject_1
# FileName:      db.py
# Author:       H_M
# Datetime:     2024/9/3 18:50
# Description:
# ---------------------------------------------------------------------------
import logging

import pymysql

from MyApiAutoTest_v2.common.read_ini import ReadIni
from MyApiAutoTest_v3 import log
from MyApiAutoTest_v3.data_config.settings import *


class DB:
    def __init__(self):
        """创建数据库连接对象和游标对象"""
        ini = ReadIni()
        self.conn = pymysql.connect(
            host=ini.get_sql(HOST),
            port=int(ini.get_sql(PORT)),
            user=ini.get_sql(USER),
            password=ini.get_sql(PASSWORD),
            database=ini.get_sql(DATABASE),
            charset="utf8"
        )
        self.cursor = self.conn.cursor()

    def delete(self, sql):
        if isinstance(sql, str):
            if sql.strip().lower().startswith("delete"):
                try:
                    self.cursor.execute(sql)
                    self.conn.commit()
                except Exception as e:
                    log.error(f"删除的sql语句错误,错误为{e}")
                    raise e
            else:
                log.error(f"不是删除的sql语句,sql语句为：{sql}")
        else:
            log.error("sql语句不是一个字符串")

    def select(self, sql):
        res = None
        if isinstance(sql, str):
            if sql.strip().lower().startswith("select"):
                try:
                    self.cursor.execute(sql)
                except Exception as e:
                    log.error(f"查询的sql语句错误,错误为{e}")
                    raise e
                else:
                    res = self.cursor.fetchall()

                if res:
                    return res[0][0]
            else:
                log.error()(f"不是查询的sql语句,sql语句为：{sql}")
        else:
            log.error("sql语句不是一个字符串")


if __name__ == '__main__':
    db = DB()
    print(db.select('select ID_ from uc_org where CODE_="limit1";'))