SQLAlchemy 事务

2021/7/29 2:35:57

本文主要是介绍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)

 



这篇关于SQLAlchemy 事务的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程