Objective
Create a Python program that makes transfers between accounts inside a transaction: if something fails, no change is applied. The connection can be used as a context manager, with con: commits on a clean exit and rolls back if there is an exception. Use an in-memory database with the sqlite3 module (sqlite3.connect(":memory:")).
Instructions
- Create the table
accountswithname(primary key, text) andbalance(integer). Readnaccounts withname balanceand docommit(). - Read
mtransfers withsource target amount. Insidewith con:subtract the amount from the source and add it to the target with twoUPDATE. - Raise
ValueErrorwithunknown sourceif the source does not exist (rowcountis 0), withunknown destinationif the target does not exist and withinsufficient balanceif the source ends up negative. - If everything goes well show
Transfer completed; if there is aValueErrorshowRejected: message. At the end showBalances:and each account asname: balance, sorted by name.
2
ana 100
luis 50
2
ana luis 30
luis ana 200
Transfer completed
Rejected: insufficient balance
Balances:
ana: 70
luis: 80
Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.
Start exercise