• SQLAlchemy 事务


    定义两个表User和Person, 先插入第一个表,抛出异常,在插入第二个表

    UserModel

    from sqlalchemy import Column, Integer, VARCHAR
    from sqlalchemy.orm import declarative_base
    
    Base = declarative_base()
    
    
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(VARCHAR(256), nullable=False)
        age = Column(Integer)
        place = Column(VARCHAR(256), nullable=False)
    
        def __init__(self, id, name, age, place):
            self.id = id
            self.name = name
            self.age = age
            self.place = place

    PersonModel

    from sqlalchemy import Column, Integer, VARCHAR
    from sqlalchemy.orm import declarative_base
    
    Base = declarative_base()
    
    
    class Person(Base):
        __tablename__ = 'person'
        id = Column(Integer, primary_key=True)
        name = Column(VARCHAR(256), nullable=False)
        age = Column(Integer)
    
        def __init__(self, id, name, age):
            self.id = id
            self.name = name
            self.age = age

    事务Demo

    from MySQLUtil import get_session
    from PersonModel import Person
    from UserModel import User
    
    
    def raise_error():
        raise Exception
    
    
    def add_user(user, person):
        session = get_session()
        session.add(user)
        raise_error()
        session.add(person)
        session.commit()
        session.close()
    
    
    def query_person():
        session = get_session()
        persons = session.query(Person).all()
        session.close()
        return persons
    
    
    if __name__ == '__main__':
        # id, name, age, place
        wangwu_user = User(id=3, name='wangwu1', age=18, place='Chengdu')
        # id, name, age
        wangwu_person = Person(id=2, name='wangwu1', age=18)
        add_user(wangwu_user, wangwu_person)
    Please call me JiangYouDang!
  • 相关阅读:
    2017.10.12
    2017.10.25
    2017.10.24
    进度条06
    课堂练习(返回一个环状一维整数数组中最大子数组的和)
    团队项目成员和题目
    团队作业--四则运算网页版
    进度条04
    个人作业(最大子数组)
    进度条03
  • 原文地址:https://www.cnblogs.com/luckygxf/p/15073314.html
Copyright © 2020-2023  润新知