手把手教你用Python搭建学工管理系统
2025-03-21 05:06
大家好,今天咱们来聊聊怎么用Python打造一个超酷的学工管理系统。这玩意儿能帮你管理学生的信息,比如名字、学号啥的,还能方便老师处理日常事务。
首先,我们需要准备一些东西:
1. Python环境(建议用Python3.x)
2. 一个数据库工具,这里我们用SQLite,因为它轻量级又简单。
### 第一步:搭建项目结构
先创建一个文件夹,叫它`student_system`,然后在里面新建两个文件:`main.py`和`db.py`。`main.py`用来运行整个程序,`db.py`负责和数据库打交道。
### 第二步:编写数据库操作代码
在`db.py`里,我们要定义几个函数,比如添加学生、删除学生、查询学生等等。代码如下:
import sqlite3 def init_db(): conn = sqlite3.connect('students.db') cursor = conn.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, student_id TEXT UNIQUE NOT NULL)''') conn.commit() conn.close() def add_student(name, student_id): conn = sqlite3.connect('students.db') cursor = conn.cursor() try: cursor.execute("INSERT INTO students (name, student_id) VALUES (?, ?)", (name, student_id)) conn.commit() print(f"学生 {name} 添加成功!") except Exception as e: print(f"添加失败:{e}") finally: conn.close() def delete_student(student_id): conn = sqlite3.connect('students.db') cursor = conn.cursor() try: cursor.execute("DELETE FROM students WHERE student_id = ?", (student_id,)) conn.commit() print(f"学号为 {student_id} 的学生删除成功!") except Exception as e: print(f"删除失败:{e}") finally: conn.close() def list_students(): conn = sqlite3.connect('students.db') cursor = conn.cursor() cursor.execute("SELECT * FROM students") rows = cursor.fetchall() if rows: for row in rows: print(row) else: print("没有找到学生记录。") conn.close()
### 第三步:编写主程序
现在到`main.py`里,写点交互逻辑,让用户可以输入指令,比如添加学生、查看学生列表啥的:
from db import * def main(): init_db() while True: print("\n学工管理系统\n1. 添加学生\n2. 删除学生\n3. 查看所有学生\n4. 退出") choice = input("请选择操作:") if choice == '1': name = input("请输入学生姓名:") student_id = input("请输入学号:") add_student(name, student_id) elif choice == '2': student_id = input("请输入要删除的学生学号:") delete_student(student_id) elif choice == '3': list_students() elif choice == '4': print("再见!") break else: print("无效选项,请重新选择。") if __name__ == "__main__": main()
### 总结
好了,这样一个简单的学工管理系统就完成了。你可以试着运行一下,看看能不能顺利地添加、删除和查看学生信息。希望这个小项目能帮到你!
如果觉得不够完善,还可以继续扩展功能,比如增加修改学生信息的功能,或者把数据存储到云端之类的。
本站知识库部分内容及素材来源于互联网,如有侵权,联系必删!
标签:学工管理系统