"""
@author: luojunhui
"""
import pymysql
from pymysql.cursors import DictCursor


class longArticlesMySQL(object):
    """
    PQ Mysql
    """
    connection = pymysql.connect(
        host='rm-bp14529nwwcw75yr1ko.mysql.rds.aliyuncs.com',
        port=3306,
        user='changwen_admin',
        password='changwen@123456',
        db='long_articles',
        charset='utf8mb4'
    )

    @classmethod
    def update(cls, sql, params):
        """
        更新
        :return:
        """
        cursor = cls.connection.cursor()
        cursor.execute(sql, params)
        affected_rows = cursor.rowcount
        cls.connection.commit()
        return affected_rows

    @classmethod
    def select(cls, sql, cursor_type=None):
        """
        查询
        :param cursor_type: 查询出结果的类型，默认None
        :param sql:
        :return:
        """
        cursor = cls.connection.cursor(cursor_type)
        cursor.execute(sql)
        result = cursor.fetchall()
        return result

    @classmethod
    def insertMany(cls, sql, params_list):
        """
        :param sql:
        :param params_list:
        :return:
        """
        cursor = cls.connection.cursor()
        try:
            cursor.executemany(query=sql, args=params_list)
            affected_rows = cursor.rowcount
            cls.connection.commit()
            return affected_rows
        except Exception as e:
            print("Insert Many Defeat--{}".format(e))
            cls.connection.rollback()
            raise e

