Python员工管理系统:连接数据库并实现增删改查
下面是一个简单的员工管理系统的Python代码,连接到数据库:
import mysql.connector
# 连接到数据库
mydb = mysql.connector.connect(
host='localhost',
user='yourusername',
password='yourpassword',
database='yourdatabase'
)
mycursor = mydb.cursor()
# 创建员工表
mycursor.execute('CREATE TABLE IF NOT EXISTS employees (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT, department VARCHAR(255))')
# 添加员工
def add_employee(name, age, department):
sql = 'INSERT INTO employees (name, age, department) VALUES (%s, %s, %s)'
val = (name, age, department)
mycursor.execute(sql, val)
mydb.commit()
print('员工已添加')
# 更新员工信息
def update_employee(id, name, age, department):
sql = 'UPDATE employees SET name = %s, age = %s, department = %s WHERE id = %s'
val = (name, age, department, id)
mycursor.execute(sql, val)
mydb.commit()
print('员工信息已更新')
# 删除员工
def delete_employee(id):
sql = 'DELETE FROM employees WHERE id = %s'
val = (id,)
mycursor.execute(sql, val)
mydb.commit()
print('员工已删除')
# 显示所有员工
def show_employees():
mycursor.execute('SELECT * FROM employees')
result = mycursor.fetchall()
for employee in result:
print(employee)
# 测试代码
add_employee('John Doe', 30, 'IT')
add_employee('Jane Smith', 35, 'HR')
show_employees()
update_employee(1, 'John Doe', 31, 'IT')
delete_employee(2)
show_employees()
注意替换以下部分:
'localhost':数据库主机名'yourusername':数据库用户名'yourpassword':数据库密码'yourdatabase':数据库名称
此代码使用mysql.connector库来连接到MySQL数据库。你需要先安装mysql-connector-python库,可以使用pip install mysql-connector-python命令进行安装。
原文地址: https://www.cveoy.top/t/topic/o5gM 著作权归作者所有。请勿转载和采集!