# -*- coding: utf-8 -*-
# @Time : 2021/10/26 19:57
# @Author : wangyinghao
# @File : handle_db.py
# @Software: PyCharm
import pymysql


class HandleDB:

    def __init__(self, host, port, user, password, databases):
        # 连接数据库，创建游标。
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.databases = databases

        # 1、建立连接
        self.conn = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            database=self.databases,
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor
        )
        # 2、创建游标
        self.cur = self.conn.cursor()

    def select_one_data(self, sql):
        self.conn.commit()
        self.cur.execute(sql)
        return self.cur.fetchone()

    def select_all_data(self, sql):
        self.conn.commit()
        self.cur.execute(sql)
        return self.cur.fetchall()

    def get_count(self, sql):
        self.conn.commit()
        return self.cur.execute(sql)

    def update(self, sql):
        """
        对数据库进行增、删、改的操作。
        :param sql:
        :return:
        """
        self.cur.execute(sql)
        self.conn.commit()

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

    def execution_results(self, sql):
        """
        获取执行结果
        :return:
        """
        self.cur.execute(sql)
        # result_one = self.cur.fetchone()
        # print("resutl1 {0}", format(result_one))  # fetchone()   获取一条结果
        # result_many = self.cur.fetchmany(3)   # fetchmany(n) 获取n条结果
        # print("resutl1 {0}", format(result_many))
        result_all = self.cur.fetchall()      # fetchall()  获取所有结果
        print("resutl1 ", format(result_all))
        self.cur.close()
