r/learnpython•
S_king_

Ensuring SQL Transactions

I have a lightweight web project running on flask with a portion of code doing two sql commands when a user "buys" stock in my stock market game. The code block:

  1. Adjust user's balance
  2. Add transaction to ledger

How do I make sure that either both of these execute or neither?

I.E. If the INSERT statement for the ledger fails I'd want to 'roll back' the update to the user's balance and give the user a warning that the transaction failed.

Try/catch doesn't seem to be the best way and putting both statements in one db.execute statement still allows one command to execute independently of the other.

(Excerpt:)

        if request.form['submit'] == 'Buy':
           try:
            db.execute("Update users ...")
            db.execute("Insert into ledger...")
           catch:
            print("SLQ ERROR!")



        

Posted Feb 16, 2017, 10:31 PM UTC

35
Loading comments…