三层架构学生管理系统简单代码
时间: 2023-07-28 20:07:40 浏览: 88
简单的三层架构代码
以下是一个简单的三层架构学生管理系统的代码示例:
业务逻辑层(BLL):
```python
from dal import StudentDAL
class StudentBLL:
def __init__(self):
self.dal = StudentDAL()
def add_student(self, student_info):
# 验证学生信息是否合法
if not self._is_valid_student_info(student_info):
return False
# 调用数据访问层保存学生信息
return self.dal.save_student(student_info)
def get_students(self):
# 调用数据访问层获取学生信息
return self.dal.get_students()
def _is_valid_student_info(self, student_info):
# 验证学生信息是否合法的方法
return True
```
数据访问层(DAL):
```python
import sqlite3
class StudentDAL:
def __init__(self):
self.conn = sqlite3.connect('students.db')
self.cursor = self.conn.cursor()
self.cursor.execute('CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, gender TEXT)')
def save_student(self, student_info):
# 保存学生信息到数据库
sql = 'INSERT INTO students (name, age, gender) VALUES (?, ?, ?)'
self.cursor.execute(sql, (student_info['name'], student_info['age'], student_info['gender']))
self.conn.commit()
return True
def get_students(self):
# 从数据库获取学生信息
sql = 'SELECT * FROM students'
self.cursor.execute(sql)
students = []
for row in self.cursor.fetchall():
student = {
'id': row[0],
'name': row[1],
'age': row[2],
'gender': row[3]
}
students.append(student)
return students
```
用户界面层(UI):
```python
from bll import StudentBLL
def main():
student_bll = StudentBLL()
while True:
print('1. 添加学生')
print('2. 查看学生列表')
print('3. 退出')
choice = input('请选择操作:')
if choice == '1':
name = input('请输入学生姓名:')
age = input('请输入学生年龄:')
gender = input('请输入学生性别:')
student_info = {
'name': name,
'age': age,
'gender': gender
}
if student_bll.add_student(student_info):
print('添加成功')
else:
print('添加失败')
elif choice == '2':
students = student_bll.get_students()
for student in students:
print(student)
elif choice == '3':
break
else:
print('无效的操作')
if __name__ == '__main__':
main()
```
需要注意的是,这只是一个简单的示例,真实的学生管理系统可能会更加复杂,需要更多的业务逻辑和界面设计。
阅读全文