python MySQL库的操作_DB库

import pymysql
from DBUtils.PooledDB import PooledDB
import time
from loguru import logger

# 数据库连接
class MysqlCline(object):
    def __init__(self, ip='localhost', port=3306, user='root', passwd='root'):
        mysql_params = {
     
            "host": ip,
            "port": port,
            "user": user,
            "passwd": passwd,
            # "charset": charset,
        }
        while True:
            try:
                self.db_pool = PooledDB(pymysql, 2, **mysql_params)
                break
            except Exception as e:
                logger.warning(f"数据库 连接 其他错误--{str(e)}")
                time.sleep(5)
                continue


# 数据库增删改查
class MysqlBasicOperation(MysqlCline):

    def select_db(self, sql):
        """查询"""

        conn = self.db_pool.connection()
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        try:
            cursor.execute(sql)
            data = cursor.fetchall()
        except Exception as e:
            data = "mysql 查询操作 出现错误!!!!!!!!!!" + str(e)
        return data

    def execute_db(self, sql, cao_zuo):
        """更新/新增/删除"""
        conn = self.db_pool.connection()
        cursor = conn.cursor()
        try:
            data_status = cursor.execute(sql)
            conn.commit()  # 提交
        except Exception as e:
            data_status = f"mysql {cao_zuo}操作 出现错误!!!!!!!!!!" + str(e) + str(sql)
            # 回滚所有更改
            conn.rollback()
        return data_status

    def mysql_insert_dan(self, table_name, item_json):
        """插入mysql数据
       @param table_name: 数据库.数据表 的形式 查找表
       @param item_json: json 数据
       @return: 返回插入状态   0-数据已经存在  1-插入成功
       """
        conn = self.db_pool.connection()  # 使用cursor()方法获取操作游标
        cursor = conn.cursor()
        keys = ','.join(item_json.keys())
        values = ','.join(['%s'] * len(item_json))
        sql = f'INSERT IGNORE INTO {table_name} ({keys}) values({values})'
        # print(sql)
        # print(tuple(item_json.values()))
        try:
            data_status = cursor.execute(sql, tuple(item_json.values()))
            conn.commit()  # 提交
        except Exception as e:
            e = "mysql 增加处 出现错误!!!!!!!!!!" + str(e)
            conn.rollback()
            data_status = e
        # cursor.close()
        # conn.close()
        # print(data_status)
        return data_status

    # 增
    def mysql_insert(self, table_name, item_json):
        keys = ','.join(item_json.keys())
        sql = f'INSERT IGNORE INTO {table_name} ({keys}) values {tuple(item_json.values())}'
        if "None" in sql:
            sql = sql.replace("None", "Null")
        data_status = self.execute_db(sql, cao_zuo='增加')
        return data_status

    # 删
    def mysql_delete(self, table_name, where_str=''):
        if not where_str:
            logger.warning("必须传值 要不然删除的是整个 数据库")
            return
        sql = f"DELETE FROM {table_name} {where_str}"
        data_status = self.execute_db(sql, cao_zuo='删除')
        return data_status

    # 改
    def mysql_updat(self, table_name, updata_str, where_str):
        sql = f"update {table_name} set {updata_str} WHERE {where_str}"
        data_status = self.execute_db(sql, cao_zuo='修改')
        return data_status

    # 查
    def mysql_select(self, table_name, *args, where_str="", sql_str=""):
        """
        :param table_name: 数据库.数据表 的形式 查找表
        :param args:  查询的字段 可以是任何东西  count(*) * "id, name"
        :param where_str: 查询条件:默认是""
        :return: 返回查询到的数据
        """
        if sql_str:
            sql = sql_str
        else:
            if where_str:
                sql = f'select {",".join(args)} from {table_name} {where_str}'
            else:
                sql = f'select {",".join(args)} from {table_name}'
        datas = self.select_db(sql)
        if args == ('count(*)',):
            datas = datas[0].get("count(*)")
        else:
            datas = datas
        return datas

    # 相当于更新插入    每个字段必须传,要不然 覆盖为 kong
    def mysql_fugai(self, table_name, item_json):
        keys = ','.join(item_json.keys())
        sql = f'REPLACE INTO {table_name} ({keys}) values {tuple(item_json.values())}'
        data_status = self.execute_db(sql, cao_zuo='覆盖')
        # print(data_status)
        # data_status 2 更新成功 1 插入数据
        return data_status

你可能感兴趣的:(mysql,python)