32 lines
707 B
Python
32 lines
707 B
Python
from schemas.student import *
|
|
from core.database import get_db
|
|
from models.student import *
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
|
def create_students(d: dict, db: Session):
|
|
stu = Student(**d)
|
|
|
|
try:
|
|
# 1. 添加到 Session
|
|
db.add(stu)
|
|
|
|
# 2. flush,让 MySQL 先生成自增 id
|
|
db.flush()
|
|
|
|
# 3. 根据 id 生成学生编号
|
|
if not stu.student_no:
|
|
stu.student_no = f"STU{stu.id:04d}"
|
|
|
|
# 4. 提交事务
|
|
db.commit()
|
|
|
|
# 5. 刷新对象,拿到数据库最终数据
|
|
db.refresh(stu)
|
|
|
|
return stu
|
|
|
|
except Exception as e:
|
|
db.rollback()
|
|
print(f"插入学生失败: {e}")
|
|
return None |