WeCodeAcademy

Transactions: All or Nothing

Some jobs need several changes that must succeed together: moving 100 cedis means taking it from one account and adding it to another. If the program fails halfway, money vanishes.

A transaction groups statements so they are applied as one unit. commit() makes them permanent; rollback() cancels them all. In Python's sqlite3, changes are held in a transaction until you commit. Use a try/except so any failure rolls everything back.

Examplepython
Open in editor »
Quick check

What does rollback() do?

Your turn: write the code

Insert a row, then roll back, and print how many rows the table holds (it should be the count from before the insert).

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.