import pymysql
from config import set_config
from log import Log

config_, env = set_config()
log_ = Log()


class MysqlHelper(object):
    def __init__(self):
        """
        初始化mysql连接信息
        """
        self.mysql_info = config_.MYSQL_INFO

    def get_data(self, sql):
        """
        查询数据
        :param sql: sql语句
        :return: data
        """
        # 连接数据库
        conn = pymysql.connect(**self.mysql_info)
        # 创建游标
        cursor = conn.cursor()
        try:
            # 执行SQL语句
            cursor.execute(sql)
            # 获取查询的所有记录
            data = cursor.fetchall()
        except Exception as e:
            return None
        # 关闭游标对象
        cursor.close()
        # 关闭数据库连接
        conn.close()
        return data

    def add_data(self, sql):
        """
        新增数据
        :param sql:
        :return:
        """
        # 连接数据库
        conn = pymysql.connect(**self.mysql_info)
        # 创建游标
        cursor = conn.cursor()
        try:
            # 执行SQL语句
            cursor.execute(sql)
            # 提交到数据库执行
            conn.commit()
        except Exception as e:
            # 发生错误时回滚
            log_.error(e)
            conn.rollback()
        # 关闭游标对象
        cursor.close()
        # 关闭数据库连接
        conn.close()


if __name__ == '__main__':
    mysql_helper = MysqlHelper()
    sql = "select * from hot_word;"
    data = mysql_helper.get_data(sql=sql)
    print(data)