定义两个表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)