You can use engine.begin
to open a connection and begin a transaction that will be rolled back if an exception is raised, or committed otherwise. This is an implicit way of using a transaction, since you don't have the option of rolling back manually.
with engine.begin() as conn:
conn.execute(products.insert(), price=15)
More explicitly, you can begin a transaction using a connection:
with conn.begin() as trans:
conn.execute(products.insert(), price=15)
Note that we still call execute
on the connection. As before, this transaction will be committed or rolled back if an exception is raised, but we also have access to the transaction, allowing us to rollback manually using trans.rollback()
.
This could be done more explicitly like so:
trans = conn.begin()
try:
conn.execute(products.insert(), price=15)
trans.commit()
except:
trans.rollback()
raise