pymysql工具类

import pymysql

class MysqlConnection(object):
    def __init__(self, config):
        self.connection = pymysql.connect(**config)
        self.connection.autocommit(True)
        self.cursor = self.connection.cursor()
    
    def reConnect(self):
        """
        重连机制
        :return:
        """
        try:
            self.connection.ping()
        except:
            self.connection()
    
    def close(self):
        """
        断开连接
        :return:
        """
        self.cursor.close()
        self.connection.close()
    
    def __del__(self):
        self.close()
    
    def queryAll(self, sql):
        """
        查询所有数据
        :param sql: sql语句
        :return:
        """
        self.reConnect()
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()
        except Exception as e:
            return e
    
    def queryMany(self, sql, n):
        """
        查询几条数据
        :param sql:
        :return:
        """
        self.reConnect()
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchmany(n)
        except Exception as e:
            return e
    
    def queryOne(self, sql):
        """
        查询一条记录
        :param sql:
        :return:
        """
        self.reConnect()
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchone()
        except Exception as e:
            return e
    
    def operate(self, sql, params=None, DML=True):
        """
        """
        self.reConnect()
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql, params)
                self.connection.commit()
                return 0
        except Exception as e:
            if DML:
                self.connection.rollback()
                return e
# 举个例子
if __name__ == "__main__":
    config = {
        'host':'192.168.153.32',
        'port':3306,
        'user':'root',
        'password':'123456',
        'db':'webapp'
    }
    msc = MysqlConnection(config)
    sql = "select * from students"
    print(msc.queryAll(sql))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值