我使用SQL鍊金術在我的項目,我用DB會話,在使用db會話時如何在sql鍊金術中使用事務?
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會話使用:
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()
如何使用trasaction?
我將使用'with db_session.begin():...',並且如果可能,刪除'try:... except:...',因爲它隱藏了所有異常。 – Governa 2012-07-27 16:21:49
'flush'也不適用。看到我的答案應該怎麼做! – schlamar 2013-01-14 14:50:14