handle_db.py 1.2 KB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2022/12/12 12:05
# @Author  : Shitou
# @FileName: handle_db.py
# @Software: PyCharm
"""
封装数据库
"""
import pymysql
from common.handle_config import conf


class DB:
    def __init__(self, host, port, password, user):
        self.con = pymysql.connect(host=host,
                                   port=port,
                                   user=user,
                                   password=password,
                                   charset="utf8",
                                   cursorclass=pymysql.cursors.DictCursor
                                   )
        # 第二步:创建一个游标对象
        self.cur = self.con.cursor()

    def find_data(self, sql):
        """查询数据"""
        # 先提交事物,同步数据库的最新状态self.con.commit(),然后在查询
        self.con.commit()
        self.cur.execute(sql)
        res = self.cur.fetchall()
        return res


db = DB(host=conf.get("mysql", "host"),
        port=conf.getint("mysql", "port"),  # 端口需要用int类型
        user=conf.get("mysql", "user"),
        password=conf.get("mysql", "password")
        )