import pymysql
from Homework_files.APITesting_LZJ.common.read_ini import ReadIni

class DB:
    def __init__(self):
        ini = ReadIni()
        try:
            self.conn = pymysql.connect(
                host=ini.connect_database_msg("host"),
                port=int(ini.connect_database_msg("port")),
                user=ini.connect_database_msg("user"),
                password=ini.connect_database_msg("pwd"),
                database=ini.connect_database_msg("database"),
                charset="utf8"
            )
            self.cursor = self.conn.cursor()
        except Exception as e:
            print("链接数据库出错,错误为:", e)
            raise e

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

    def delete(self, sql_sentence):
        try:
            self.cursor.execute(sql_sentence)
        except Exception as e:
            print("执行删除的sql语句时报错,错误为:", e)
            raise e
        else:
            self.conn.commit()

    def select(self, sql_sentence):
        try:
            self.cursor.execute(sql_sentence)
        except Exception as e:
            print("执行查询的sql语句时报错,错误为:", e)
            raise e
        else:
            select_result = self.cursor.fetchall()
            if select_result:
                return select_result[0][0]