# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   框架
# FileName:      db.py
# Author:       xxxxxxx
# Datetime:     2023/11/4 14:06
# Description:
# 命名规范：文件名全小写+下划线，类名大驼峰，方法和变量小写+下划线连接，
# 常量大写，变量和常量用名词，方法用动词
# ---------------------------------------------------------------------------
import pymysql

from InterfaceAutoTest_2.common import log
from InterfaceAutoTest_2.common.read_ini import ReadIni


class DB:
    def __init__(self):
        """连接数据库，获取连接对象和游标对象"""
        read_ini = ReadIni()
        try:
            self.conn = pymysql.connect(
                host=read_ini.get_sql_message("host"),
                port=read_ini.get_sql_message("port"),
                user=read_ini.get_sql_message("user"),
                password=read_ini.get_sql_message("pwd"),
                database=read_ini.get_sql_message("database"),
                charset="utf-8"
            )
            self.cursor = self.conn.cursor()
        except:
            log.error("连接数据库错误或获取游标对象失败")
            raise pymysql.MySQLError("连接数据库错误或获取游标对象失败")

    def close(self):
        self.cursor.close()
        self.conn.close()

    def delete(self, sql):
        """执行删除的sql语句"""
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except:
            log.error("执行删除的sql语句错误，请查看对应的sql语句")
            raise ValueError("执行删除的sql语句错误，请查看对应的sql语句")

    def select(self, sql, num=None):
        """执行查询的sql语句"""
        try:
            self.cursor.execute(sql)
            select_result = self.cursor.fetchall()
            if select_result:
                return select_result[0][0]
            elif select_result and num == 2:
                return select_result[0][0], select_result[0][1]
            elif select_result and num > 3:
                return select_result
        except:
            log.error("执行查询的sql语句错误，请查看对应的sql语句")
            raise ValueError("执行查询的sql语句错误，请查看对应的sql语句")