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])
    查询数据
  • 相关阅读:
    2014.12.31今年最后的一天
    leetcode11 盛最多水的容器(Medium)
    leetcode23 合并k个排序链表(Hard)
    leetcode148 排序链表(Medium)
    leetcode48 旋转图像(Medium)
    leetcode227基本计算器II (Medium)
    leetcode338 比特位计数(Medium)
    leetcode32 最长有效括号(Hard)
    leetcode面试题10.01 合并排序的数组(Easy)
    leetcode55 跳跃游戏(Medium)
  • 原文地址:https://www.cnblogs.com/Treasuremy/p/10385698.html
Copyright © 2011-2022 走看看