Python员工管理系统代码
时间: 2024-06-15 15:02:12 浏览: 204
创建一个简单的Python员工管理系统代码示例通常包括以下几个主要部分:员工类定义、数据库操作(例如使用SQLite或ORM库)以及基本的管理功能,如添加、删除、更新和查询员工信息。这里提供一个基础框架,但请注意实际项目可能需要更复杂的数据结构和错误处理:
```python
import sqlite3
# 员工类
class Employee:
def __init__(self, id, name, position, salary):
self.id = id
self.name = name
self.position = position
self.salary = salary
def __str__(self):
return f"ID: {self.id}, Name: {self.name}, Position: {self.position}, Salary: {self.salary}"
# 连接到SQLite数据库
def connect_database(db_name="employees.db"):
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS employees
(id INTEGER PRIMARY KEY, name TEXT, position TEXT, salary REAL)''')
return conn, cursor
# 添加员工
def add_employee(employee, conn, cursor):
cursor.execute("INSERT INTO employees VALUES (?, ?, ?, ?)", employee.__dict__.values())
conn.commit()
# 删除员工
def delete_employee(id, conn, cursor):
cursor.execute(f"DELETE FROM employees WHERE id = ?", (id,))
conn.commit()
# 更新员工信息
def update_employee(id, updated_employee, conn, cursor):
cursor.execute("UPDATE employees SET name = ?, position = ?, salary = ? WHERE id = ?", updated_employee)
conn.commit()
# 查询员工
def get_employee(id, conn, cursor):
cursor.execute("SELECT * FROM employees WHERE id = ?", (id,))
return cursor.fetchone()
# 示例使用
if __name__ == "__main__":
# 初始化连接
conn, cursor = connect_database()
# 创建一个员工对象
emp1 = Employee(1, "Alice", "Developer", 60000)
# 添加员工
add_employee(emp1, conn, cursor)
# 更新员工信息
updated_emp = Employee(1, "Alice Smith", "Senior Developer", 70000)
update_employee(1, updated_emp, conn, cursor)
# 查询员工
print(get_employee(1, conn, cursor))
# 关闭连接
conn.close()
阅读全文