import pymysql
from DBUtils.PooledDB import PooledDB


# 连接mysql
class LinkMysql(object):
    def __init__(self, db_info):
        self.POOLMYSQL = PooledDB(
            creator=pymysql,
            maxconnections=6,
            mincached=2,
            blocking=True,
            ping=0,

            host=db_info.get("host"),
            port=db_info.get("port"),
            user=db_info.get("user"),
            password=db_info.get("pwd"),
            database=db_info.get("database"),
            charset='utf8'
        )

    # 查询
    def query_mysql(self, sql):
        conn = self.POOLMYSQL.connection()
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result

    # 修改
    def perform_mysql(self, sql):
        conn = self.POOLMYSQL.connection()
        cursor = conn.cursor()
        cursor.execute(sql)
        last_id = cursor.lastrowid
        conn.commit()
        cursor.close()
        conn.close()
        return last_id

    # 执行
    def excete_mysql(self, sql):
        conn = self.POOLMYSQL.connection()
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cursor.execute(sql)
