把增删查改写成函数
时间: 2023-11-11 14:13:12 浏览: 69
好的,下面是将增删查改操作封装成函数的示例代码:
```python
import pymysql
# 连接数据库
def connect_db():
conn = pymysql.connect(host='localhost', user='root', password='password', database='mydb')
return conn
# 关闭数据库连接
def close_db(conn, cur):
cur.close()
conn.close()
# 查询数据
def select_data(table, columns, condition):
conn = connect_db()
cur = conn.cursor()
sql = "SELECT %s FROM %s WHERE %s" % (columns, table, condition)
cur.execute(sql)
result = cur.fetchall()
close_db(conn, cur)
return result
# 插入数据
def insert_data(table, columns, values):
conn = connect_db()
cur = conn.cursor()
sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, columns, values)
cur.execute(sql)
conn.commit()
close_db(conn, cur)
# 更新数据
def update_data(table, set_values, condition):
conn = connect_db()
cur = conn.cursor()
sql = "UPDATE %s SET %s WHERE %s" % (table, set_values, condition)
cur.execute(sql)
conn.commit()
close_db(conn, cur)
# 删除数据
def delete_data(table, condition):
conn = connect_db()
cur = conn.cursor()
sql = "DELETE FROM %s WHERE %s" % (table, condition)
cur.execute(sql)
conn.commit()
close_db(conn, cur)
```
使用时可以直接调用这些函数,例如:
```python
# 查询student表中所有年龄为20的学生
result = select_data('student', '*', 'age=20')
print(result)
# 向student表中插入一条数据
insert_data('student', 'name, age, sex', "'Tom', 20, 'male'")
# 将student表中所有年龄为20的学生的性别改为'female'
update_data('student', "sex='female'", 'age=20')
# 删除student表中所有性别为'female'的学生
delete_data('student', "sex='female'")
```
这样做的好处是可以将数据库操作的细节封装起来,提高了代码可读性和可维护性。
阅读全文