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()
相关推荐
2401_854391084 分钟前
Spring Boot大学生就业招聘系统的开发与部署
java·spring boot·后端
虽千万人 吾往矣25 分钟前
golang gorm
开发语言·数据库·后端·tcp/ip·golang
这孩子叫逆1 小时前
Spring Boot项目的创建与使用
java·spring boot·后端
coderWangbuer2 小时前
基于springboot的高校招生系统(含源码+sql+视频导入教程+文档+PPT)
spring boot·后端·sql
攸攸太上2 小时前
JMeter学习
java·后端·学习·jmeter·微服务
Kenny.志2 小时前
2、Spring Boot 3.x 集成 Feign
java·spring boot·后端
sky丶Mamba3 小时前
Spring Boot中获取application.yml中属性的几种方式
java·spring boot·后端
千里码aicood4 小时前
【2025】springboot教学评价管理系统(源码+文档+调试+答疑)
java·spring boot·后端·教学管理系统
程序员-珍4 小时前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
liuxin334455664 小时前
教育技术革新:SpringBoot在线教育系统开发
数据库·spring boot·后端