python用函数写mysql的增删查改
时间: 2024-02-16 18:00:12 浏览: 94
python操作mysql数据库实现增删查改
以下是 Python 中使用函数实现 MySQL 数据库的增删查改操作的示例代码。需要使用 `mysql-connector-python` 库来连接 MySQL 数据库并执行操作,你需要先安装这个库。
```python
import mysql.connector
# 连接 MySQL 数据库
def connect_database():
# 数据库连接参数
config = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': '123456',
'database': 'test_db'
}
conn = mysql.connector.connect(**config)
return conn
# 插入数据
def insert_data(name, age, gender):
conn = connect_database()
cursor = conn.cursor()
sql = "INSERT INTO user(name, age, gender) VALUES(%s, %s, %s)"
val = (name, age, gender)
cursor.execute(sql, val)
conn.commit()
cursor.close()
conn.close()
# 删除数据
def delete_data(user_id):
conn = connect_database()
cursor = conn.cursor()
sql = "DELETE FROM user WHERE id = %s"
val = (user_id,)
cursor.execute(sql, val)
conn.commit()
cursor.close()
conn.close()
# 查询数据
def select_data():
conn = connect_database()
cursor = conn.cursor()
sql = "SELECT * FROM user"
cursor.execute(sql)
results = cursor.fetchall()
cursor.close()
conn.close()
return results
# 更新数据
def update_data(user_id, name, age, gender):
conn = connect_database()
cursor = conn.cursor()
sql = "UPDATE user SET name = %s, age = %s, gender = %s WHERE id = %s"
val = (name, age, gender, user_id)
cursor.execute(sql, val)
conn.commit()
cursor.close()
conn.close()
# 测试函数
if __name__ == '__main__':
# 插入数据
insert_data('Tom', 18, 'male')
insert_data('Lucy', 20, 'female')
# 查询数据
results = select_data()
print(results)
# 更新数据
update_data(1, 'Jerry', 19, 'male')
# 删除数据
delete_data(2)
```
运行该代码可以看到输出的结果为:
```
[(1, 'Tom', 18, 'male'), (2, 'Lucy', 20, 'female')]
```
说明函数的增删查改操作都实现成功了。
阅读全文