"""
@author: luojunhui
"""
import pymysql
from applications.decoratorApi import retryOnTimeout


class PQMySQL(object):
    """
    PQ Mysql
    """

    def __init__(self):
        self.connection = None
        self.connect_to_db()

    @retryOnTimeout()
    def connect_to_db(self):
        """
        连接 数据库
        :return:
        """
        self.connection = pymysql.connect(
            host='rm-bp1159bu17li9hi94.mysql.rds.aliyuncs.com',
            port=3306,
            user='crawler',
            password='crawler123456@',
            db='piaoquan-crawler',
            charset='utf8mb4',
            connect_timeout=120
        )

    def insert(self, sql, params):
        """
        更新
        :return:
        """
        cursor = self.connection.cursor()
        try:
            cursor.execute(sql, params)
            affected = cursor.rowcount
            self.connection.commit()
            return affected
        except Exception as e:
            self.connection.rollback()
            raise e

    def update(self, sql, params):
        """
        更新
        :return:
        """
        cursor = self.connection.cursor()
        try:
            cursor.execute(sql, params)
            affected = cursor.rowcount
            self.connection.commit()
            return affected
        except Exception as e:
            self.connection.rollback()
            raise e

    def select(self, sql):
        """
        查询
        :param sql:
        :return:
        """
        cursor = self.connection.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        return result

    def insertMany(self, sql, params_list):
        """
        :param sql:
        :param params_list:
        :return:
        """
        cursor = self.connection.cursor()
        try:
            cursor.executemany(query=sql, args=params_list)
            affected = cursor.rowcount
            self.connection.commit()
            return affected
        except Exception as e:
            self.connection.rollback()
            raise e
