把以上的 增 删 改 查 函数包装到类中
时间: 2024-03-28 11:37:23 浏览: 59
封装了一个Hibernate增删改查的工具类
4星 · 用户满意度95%
把以上的增删改查函数包装到类中可以更好地组织代码,提高代码的可读性和可维护性。下面是一个使用类封装的示例:
```python
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`,它们与之前的函数实现基本相同。使用类封装的优势在于可以更好地组织代码,使代码更加简洁和易于维护。
阅读全文