python,基于花名册.excel文件,完成一个学员管理系统。学员信息的增删改查(查询所有,以及按照名称的模糊查询)、文件同步,随机点名,帮我写一个可以运行并且连接上数据库的代码。
时间: 2024-11-25 15:17:16 浏览: 18
Python 提供了丰富的库,如pandas处理Excel文件,sqlite3操作SQLite数据库,os用于文件操作等,可以帮助我们实现一个简单的学员管理系统。下面是一个基本框架的示例,假设我们将使用SQLite作为数据库存储,因为它的轻量级特性适合小规模应用:
```python
import sqlite3
import pandas as pd
# 连接SQLite数据库 (如果数据库不存在会自动创建)
def create_database():
conn = sqlite3.connect('students.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS students
(name TEXT, id INTEGER PRIMARY KEY)''')
return conn
# 插入学员信息
def add_student(name):
conn = create_database()
c = conn.cursor()
c.execute("INSERT INTO students VALUES (?, ?)", (name, len(conn.execute("SELECT * FROM students").fetchall()) + 1))
conn.commit()
print(f"Student {name} added successfully.")
# 删除学员
def delete_student(name):
conn = create_database()
c = conn.cursor()
c.execute("DELETE FROM students WHERE name=?", (name,))
conn.commit()
print(f"Student {name} deleted.")
# 更新学员信息
def update_student(name, new_name):
conn = create_database()
c = conn.cursor()
c.execute("UPDATE students SET name=? WHERE name=?", (new_name, name))
conn.commit()
print(f"Name of student {name} updated to {new_name}.")
# 查询学员列表,模糊匹配
def search_students(query):
conn = create_database()
c = conn.cursor()
result = c.execute("SELECT * FROM students WHERE name LIKE ?", ('%' + query + '%',)).fetchall()
return [dict(row) for row in result]
# 随机点名
def random_call():
conn = create_database()
c = conn.cursor()
student_count = c.execute("SELECT COUNT(*) FROM students").fetchone()[0]
if student_count > 0:
selected_student = c.execute("SELECT name FROM students ORDER BY RANDOM() LIMIT 1").fetchone()[0]
print(f"Today's random call is {selected_student}.")
else:
print("No students found.")
if __name__ == "__main__":
# 示例操作
add_student("张三")
delete_student("李四")
update_student("王五", "王晓")
print(search_students("王")) # 模糊查询
random_call()
#
阅读全文