使用装饰器和with来编写以上查询 更新 删除 函数
时间: 2024-03-27 17:40:23 浏览: 15
可以使用装饰器和`with`语句来编写通用的查询、更新和删除函数,以便在项目中重复使用。下面是一个使用装饰器和`with`语句编写的示例:
```python
import pymysql
# 定义装饰器
def with_connection(func):
def wrapper(*args, **kwargs):
with pymysql.connect(host='localhost', port=3306, user='root', password='', database='test') as conn:
result = func(conn, *args, **kwargs)
return result
return wrapper
# 查询函数
@with_connection
def select_all(conn, table):
with conn.cursor() as cursor:
cursor.execute(f'select * from {table}')
result = cursor.fetchall()
return result
# 更新函数
@with_connection
def update(conn, table, data, condition):
with 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}')
conn.commit()
return cursor.rowcount
# 删除函数
@with_connection
def delete(conn, table, condition):
with conn.cursor() as cursor:
cursor.execute(f'delete from {table} where {condition}')
conn.commit()
return cursor.rowcount
```
在上述示例中,我们定义了一个装饰器`with_connection`,用于创建数据库连接和关闭连接。然后,我们定义了三个通用的函数`select_all`、`update`和`delete`,它们都打上了`with_connection`的装饰器。这样,当调用这些函数时,就可以自动创建连接和关闭连接,使代码更加简洁和优雅。