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()
相关推荐
B1118521Y461 天前
flask的使用
后端·python·flask
xuxie131 天前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
重生成为编程大王1 天前
Java中的多态有什么用?
java·后端
Funcy1 天前
XxlJob 源码分析03:执行器启动流程
后端
豌豆花下猫1 天前
Python 潮流周刊#118:Python 异步为何不够流行?(摘要)
后端·python·ai
秋难降1 天前
SQL 索引突然 “罢工”?快来看看为什么
数据库·后端·sql
Access开发易登软件1 天前
Access开发导出PDF的N种姿势,你get了吗?
后端·低代码·pdf·excel·vba·access·access开发
中国胖子风清扬1 天前
Rust 序列化技术全解析:从基础到实战
开发语言·c++·spring boot·vscode·后端·中间件·rust
bobz9651 天前
分析 docker.service 和 docker.socket 这两个服务各自的作用
后端
野犬寒鸦1 天前
力扣hot100:旋转图像(48)(详细图解以及核心思路剖析)
java·数据结构·后端·算法·leetcode