python选课系统作业
时间: 2025-01-07 21:37:24 浏览: 0
### Python 开发学生选课系统示例
#### 创建项目环境
为了构建一个稳定可靠的学生选课系统,建议使用虚拟环境来隔离依赖项。通过命令行工具安装并激活虚拟环境:
```bash
python -m venv myenv
source myenv/bin/activate # Linux 或 macOS
myenv\Scripts\activate # Windows
```
接着,在环境中安装必要的包,如 `PyQt6` 和 `mysql-connector-python`。
```bash
pip install PyQt6 mysql-connector-python
```
#### 数据库连接模块
定义用于处理 MySQL 数据库操作的基础类,以便于后续的功能扩展和维护[^1]。
```python
import mysql.connector
class DatabaseConnection:
def __init__(self, host="localhost", user="root", password="", database=""):
self.connection = None
try:
self.connection = mysql.connector.connect(
host=host,
user=user,
passwd=password,
db=database
)
if self.connection.is_connected():
print("Successfully connected to the database.")
except Exception as e:
print(f"Error connecting to MySQL platform: {e}")
def execute_query(self, query, params=None):
cursor = self.connection.cursor()
result = None
try:
cursor.execute(query, params)
result = cursor.fetchall()
self.connection.commit()
except Exception as error:
print(f"The error '{error}' occurred")
finally:
if cursor is not None and self.connection is not None:
cursor.close()
return result
def close_connection(self):
if self.connection is not None:
self.connection.close()
```
#### 主窗口设计
利用 Qt Designer 设计图形化界面,并将其转换成 Python 文件。这里展示如何加载 `.ui` 文件以及初始化主窗口中的组件[^2]。
```python
from PyQt6 import uic
from PyQt6.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('main_window.ui', self)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
#### 功能逻辑实现
针对具体业务需求编写相应的函数,比如添加新课程、删除已有课程、显示所有可选项等。下面给出部分核心方法的伪代码表示形式[^3]。
```python
def add_course(course_name, teacher_name, max_students):
"""向数据库中插入一条新的课程记录"""
pass
def remove_course_by_id(course_id):
"""根据ID移除指定的一门课程"""
pass
def list_all_courses():
"""获取当前学期开设的所有课程列表"""
pass
def enroll_student(student_id, selected_courses_ids):
"""允许某位同学注册选定的若干门科目"""
# 验证是否有重复报名情况发生
existing_selections = get_current_enrollment_status(student_id)
conflicting_timeslots = check_time_conflicts(selected_courses_ids + existing_selections)
if conflicting_timeslots:
raise ValueError("Selected courses contain time conflicts!")
total_credits = sum([get_credit_hours(cid) for cid in selected_courses_ids])
if total_credits > MAX_CREDITS_PER_SEMESTER:
raise ValueError("Total credits exceed limit!")
update_database_with_new_selections(student_id, selected_courses_ids)
def drop_selected_courses(student_id, deselected_courses_ids):
"""取消已登记的选择"""
pass
```
阅读全文