Sobes.tech
Junior — Middle

How do you implement transaction management when working with a database?

sobes.tech AI

Answer from AI

In Python, transaction management when working with a database is usually implemented using context managers or explicit control with commit and rollback methods.

For example, when using the sqlite3 library, you can do the following:

import sqlite3

conn = sqlite3.connect('example.db')
try:
    with conn:
        conn.execute("INSERT INTO users (name) VALUES (?)", ('Alice',))
        # If an exception occurs here, the transaction will automatically rollback
except Exception as e:
    print(f"Error: {e}")
finally:
    conn.close()

The context manager with conn: automatically calls commit() upon successful completion of the block and rollback() if an exception occurs.

If the context manager is not used, you can explicitly call:

conn = sqlite3.connect('example.db')
cursor = conn.cursor()
try:
    cursor.execute("INSERT INTO users (name) VALUES (?)", ('Bob',))
    conn.commit()
except Exception:
    conn.rollback()
finally:
    conn.close()

Thus, transaction management ensures data integrity and allows rolling back changes in case of errors.