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()
相关推荐
Aerkui31 分钟前
Go 泛型(Generics)详解
开发语言·后端·golang
clive.li33 分钟前
go-webmvc框架推荐
开发语言·后端·golang
树獭叔叔39 分钟前
从向量到文字:Transformer 的预测与输出(LM Head)
后端·aigc
橙序员小站1 小时前
架构图不再手画:用 LikeC4 + AI,让架构“活”起来
后端·架构
JavaGuide2 小时前
又一款国产开源企业级文件管理系统诞生了!基于 Spring Boot 3.5.x + Sa-Token + MyBatis Flex
后端·github
大鹏19882 小时前
Go 实战 LeetCode 151:高效翻转字符串中的单词(含空格处理技巧)
后端
花果山总钻风2 小时前
SQLAlchemy各种排序示例
后端·python·中间件
uzong2 小时前
管理者不要被琐事耗尽心力
后端
最贪吃的虎2 小时前
windows上如何可视化访问并远程操作linux系统上运行的浏览器或者linux可视化桌面
java·linux·运维·windows·分布式·后端·架构