我在我的项目中使用 sql alchemy,我使用了 db session,
engine = create_engine(configuration)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
import models
Base.metadata.create_all(bind=engine)
数据库会话用作:
db_session.merge(order) #order(model) in object
db_session.commit()
现在我想将数据插入两个表订单和订单行项目,所以我需要事务,如: 1. 在第一个插入中,我希望插入的订单的 id 在第二个插入查询中使用 2. 如果第二个插入查询失败,那么第一个查询应该回滚
Try:
#begin transaction/How to begin transaction?
order=db_session.add(order) #insert into order
#is need to commit db_session here as I need inserted orders id
#here actually db_session.commit() needed to get order's id(auto generated)
#if db_session committed here then sql alchemy starts new session
order_line_item.id = order.id
db_session.add(order_line_item) #insert into order line line item
db_session.commit()
#check transaction status if failed then rollback, How to check status?
except:
db_session.rollback()
如何使用交易?