Sobes.tech
Junior — Middle

How do you implement and manage transactions when performing data update operations?

sobes.tech AI

Answer from AI

In Python, transaction management during data updates is usually handled using context managers, which automatically start, commit, or rollback transactions.

For example, when working with a database through the sqlite3 library:

import sqlite3

conn = sqlite3.connect('example.db')

try:
    with conn:
        conn.execute("UPDATE users SET balance = balance - 100 WHERE id = ?", (user_id,))
        conn.execute("UPDATE users SET balance = balance + 100 WHERE id = ?", (recipient_id,))
    # If no exceptions occur within the with block, the transaction is automatically committed
except Exception as e:
    # If an exception occurs, the transaction is automatically rolled back
    print(f"Error updating data: {e}")

If using an ORM, such as SQLAlchemy, transactions can be controlled through sessions:

from sqlalchemy.orm import Session

with Session(engine) as session:
    try:
        # update operations
        session.commit()
    except:
        session.rollback()
        raise

Thus, transactions ensure data integrity: either all update operations succeed, or in case of an error, changes are rolled back.