通用数据库连接

把以上的增删改查函数包装到类中可以更好地组织代码,提高代码的可读性和可维护性。下面是一个使用类封装的示例:

复制
import pymysql

class MySQL:
    def __init__(self, host='localhost', port=3306, user='root', password='', database=None):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        
    def __enter__(self):
        self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, database=self.database)
        return self
        
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.close()
        
    def select_all(self, table):
        with self.conn.cursor() as cursor:
            cursor.execute(f'select * from {table}')
            result = cursor.fetchall()
        return result
    
    def update(self, table, data, condition):
        with self.conn.cursor() as cursor:
            set_clause = ', '.join([f'{k}="{v}"' for k, v in data.items()])
            cursor.execute(f'update {table} set {set_clause} where {condition}')
            self.conn.commit()
        return cursor.rowcount
    
    def delete(self, table, condition):
        with self.conn.cursor() as cursor:
            cursor.execute(f'delete from {table} where {condition}')
            self.conn.commit()
        return cursor.rowcount
    
    def insert(self, table, data):
        with self.conn.cursor() as cursor:
            keys = ', '.join(data.keys())
            values = ', '.join([f'"{v}"' for v in data.values()])
            cursor.execute(f'insert into {table} ({keys}) values ({values})')
            self.conn.commit()
        return cursor.lastrowid
在上述示例中,我们定义了一个MySQL类,它包含了初始化方法、__enter__方法和__exit__方法。初始化方法用于初始化数据库连接参数,__enter__方法创建数据库连接并返回类实例,__exit__方法关闭数据库连接。除此之外,我们还定义了四个通用的方法:select_all、update、delete和insert,它们与之前的函数实现基本相同。使用类封装的优势在于可以更好地组织代码,使代码更加简洁和易于维护。
posted @ 2023-06-12 17:06  热爱技术的小牛  阅读(7)  评论(0编辑  收藏  举报
热爱技术的小牛