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()
相关推荐
深栈解码13 分钟前
JMM深度解析(三) volatile实现机制详解
java·后端
张家宝683720 分钟前
ambari
后端
StephenCurryFans23 分钟前
Spring AI vs LangChain4j:Java AI开发框架完整对比指南 🚀
后端·spring
程序员辉哥26 分钟前
学会在Cursor中使用Rules生成代码后可以躺平了吗?
前端·后端
Brookty28 分钟前
【MySQL】JDBC编程
java·数据库·后端·学习·mysql·jdbc
_代号00731 分钟前
MySQL梳理一:整体架构概览
后端·mysql
前端付豪35 分钟前
11、打造自己的 CLI 工具:从命令行到桌面效率神器
后端·python
前端付豪35 分钟前
12、用类写出更可控、更易扩展的爬虫框架🕷
后端·python
今夜星辉灿烂35 分钟前
nestjs微服务-系列2
javascript·后端
世界哪有真情1 小时前
用虚拟IP扩容端口池:解决高并发WebSocket端口耗尽问题
前端·后端·websocket