Python 员工管理系统:连接 MySQL 数据库
以下是一个简单的员工管理系统的 Python 代码示例,连接 MySQL 数据库:
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host='localhost',
user='yourusername',
password='yourpassword',
database='yourdatabase'
)
# 创建游标对象
cursor = mydb.cursor()
# 创建员工表
cursor.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)
cursor.execute(sql, val)
mydb.commit()
print(cursor.rowcount, '记录插入成功。')
# 更新员工信息
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)
cursor.execute(sql, val)
mydb.commit()
print(cursor.rowcount, '记录更新成功。')
# 删除员工
def delete_employee(id):
sql = 'DELETE FROM employees WHERE id = %s'
val = (id,)
cursor.execute(sql, val)
mydb.commit()
print(cursor.rowcount, '记录删除成功。')
# 查询所有员工
def get_all_employees():
cursor.execute('SELECT * FROM employees')
result = cursor.fetchall()
for row in result:
print(row)
# 查询特定员工
def get_employee(id):
sql = 'SELECT * FROM employees WHERE id = %s'
val = (id,)
cursor.execute(sql, val)
result = cursor.fetchone()
print(result)
# 测试代码
add_employee('John Doe', 30, 'IT')
add_employee('Jane Smith', 25, 'Marketing')
update_employee(1, 'John Doe', 31, 'IT')
delete_employee(2)
get_all_employees()
get_employee(1)
# 关闭数据库连接
mydb.close()
请确保在运行代码之前已经安装了mysql-connector-python模块。可以使用以下命令安装:
pip install mysql-connector-python
在代码中,首先使用mysql.connector.connect()函数连接到 MySQL 数据库。然后使用游标对象执行 SQL 查询和操作。最后,使用mydb.close()关闭数据库连接。
注意:请将yourusername、yourpassword和yourdatabase替换为实际的数据库用户名、密码和数据库名。
原文地址: https://www.cveoy.top/t/topic/o5fo 著作权归作者所有。请勿转载和采集!