zoukankan      html  css  js  c++  java
  • SQLAlchemy的使用---外键ForeignKey数据增删改查

    # 添加数据
    from sqlalchemy.orm import sessionmaker
    from create_table_ForeignKey import engine, Student, School
    
    Session = sessionmaker(engine)
    db_session = Session()
    
    # 插入数据
    sch_obj = School(name='Treasure')
    db_session.add(sch_obj)
    db_session.commit()
    
    
    sch = db_session.query(School).filter(School.name == 'Treasure').first()
    stu_obj = Student(name='徐建', school_id=sch.id)
    db_session.add(stu_obj)
    db_session.commit()
    db_session.close()
    
    #2 添加数据 - 反向relationship
    
    sch_obj = School(name='TreasureShanghai')
    sch_obj.sch2stu = [Student(name='徐建-上海'),
                       Student(name='徐建2-上海')]
    db_session.add(sch_obj)
    db_session.commit()
    db_session.close()
    
    #3.添加数据 - 正向relationship
    stu_obj = Student(name='徐建3', stu2sch=School(name='TreasreShenzhen'))
    db_session.add(stu_obj)
    db_session.commit()
    db_session.close()
    添加数据
    # 修改数据
    from sqlalchemy.orm import sessionmaker
    from create_table_ForeignKey import engine, Student, School
    
    Session = sessionmaker(engine)
    db_session = Session()
    
    sch = db_session.query(School).filter(School.name == 'TreasureShanghai').first()
    db_session.query(Student).filter(Student.school_id == sch.id).delete()
    db_session.commit()
    db_session.close()
    删除数据
    # 修改数据
    from sqlalchemy.orm import sessionmaker
    from create_table_ForeignKey import engine, Student, School
    
    Session = sessionmaker(engine)
    db_session = Session()
    
    sch = db_session.query(School).filter(School.name == 'Treasure').first()
    db_session.query(Student).filter(Student.name == '徐建3').update({'school_id':sch.id})
    db_session.commit()
    db_session.close()
    修改数据
    # 查询数据
    from sqlalchemy.orm import sessionmaker
    from create_table_ForeignKey import engine, Student, School
    
    Session = sessionmaker(engine)
    db_session = Session()
    
    # 查询数据 relationship 正向
    stu = db_session.query(Student).all()
    
    for row in stu:
        print(row.id, row.name, row.stu2sch.name)
    
    
    # 查询数据 relationship 反向
    sch = db_session.query(School).all()
    
    for row in sch:
        print(row.id, row.name, [i.name for i in row.sch2stu])
    查询数据
  • 相关阅读:
    The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
    线程安全思考
    微服务网关哪家强?一文看懂Zuul, Nginx, Spring Cloud, Linkerd性能差异
    从构建分布式秒杀系统聊聊分布式锁
    基于Redis实现延时队列服务
    Redis分布式锁的正确实现方式
    探究 Redis 4 的 stream 类型
    JAVA 异常分类与理解
    缓存穿透,缓存击穿,缓存雪崩解决方案分析
    分布式之数据库和缓存双写一致性方案解析(一)
  • 原文地址:https://www.cnblogs.com/Treasuremy/p/10385698.html
Copyright © 2011-2022 走看看