python之pymysql

python 复制代码
import pymysql

class DB:
    localhost = {
        'host': 'localhost',
        'user': 'root',
        'password': 'ccc3#dd599',
        'database': 'test'
    }

    dev = {
        'host': 'localhost',
        'user': 'root',
        'password': 'ccc3#dd599',
        'database': 'test'
    }

    def __init__(self, env):
        print("初始化方法调用.....")

        self.dev = DB.dev
        self.localhost = DB.localhost

        if env == 'localhost':
            self.connection = pymysql.connect(host=self.localhost['host'], user=self.localhost['user'], password=self.localhost['password'], database=self.localhost['database'])
            self.cursor = self.connection.cursor()
        elif env == 'dev':
            self.connection = pymysql.connect(host=self.dev['host'], user=self.dev['user'], password=self.dev['password'],database=self.dev['database'])
            self.cursor = self.connection.cursor()

    def __del__(self):
        print("销毁方法调用.....")
        self.connection.close()
        self.cursor.close()

    # 更新,参数类型是元组
    def update(self, sql, params):
        try:
            self.cursor.execute(sql, params)
            self.connection.commit()

            return self.cursor.rowcount
        except Exception as e:
            self.connection.rollback()
            print(e)
            return 0

    # 批量插入,params_list类型是列表,里面数据是元组[(), (), ()]
    def insetMany(self, sql, params_list):
        try:
            self.cursor.executemany(sql, params_list)
            self.connection.commit()
            return self.cursor.rowcount
        except Exception as e:
            self.connection.rollback()
            print(e)
            return 0

    # 查询, condition类型是元组
    def select(self, sql, condition=None):
        self.cursor.execute(sql, condition)
        return self.cursor.fetchall()
相关推荐
面朝大海,春不暖,花不开8 分钟前
自定义Spring Boot Starter的全面指南
java·spring boot·后端
钡铼技术ARM工业边缘计算机42 分钟前
【成本降40%·性能翻倍】RK3588边缘控制器在安防联动系统的升级路径
后端
CryptoPP1 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
白宇横流学长1 小时前
基于SpringBoot实现的大创管理系统设计与实现【源码+文档】
java·spring boot·后端
草捏子2 小时前
状态机设计:比if-else优雅100倍的设计
后端
考虑考虑3 小时前
Springboot3.5.x结构化日志新属性
spring boot·后端·spring
涡能增压发动积3 小时前
一起来学 Langgraph [第三节]
后端
sky_ph4 小时前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
涡能增压发动积4 小时前
一起来学 Langgraph [第二节]
后端
hello早上好4 小时前
Spring不同类型的ApplicationContext的创建方式
java·后端·架构