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()
相关推荐
程序员爱钓鱼9 小时前
Python编程实战:面向对象与进阶语法——类型注解与代码规范(PEP 8)
后端·python·ipython
程序员爱钓鱼9 小时前
Python实战:用高德地图API批量获取地址所属街道并写回Excel
后端·python·ipython
Yeats_Liao9 小时前
时序数据库系列(三):InfluxDB数据写入Line Protocol详解
数据库·后端·时序数据库
王元_SmallA9 小时前
Redis Desktop Manager(Redis可视化工具)安装
java·后端
好好研究9 小时前
Spring框架 - 开发方式
java·后端·spring
hashiqimiya10 小时前
springboot后端的接口headers
java·spring boot·后端
ss27310 小时前
Springboot + vue 医院管理系统
vue.js·spring boot·后端
间彧11 小时前
InfluxDB详解与应用实战
后端
间彧11 小时前
对比InfluxDB与Prometheus在监控场景下的特点及选型建议
后端