Sobes.tech
Junior — Middle

Have you had practical experience managing transactions when working with databases?

sobes.tech AI

Answer from AI

Yes, I have experience managing transactions when working with databases in Python. I usually use libraries such as sqlite3, psycopg2, or ORM tools like SQLAlchemy that support transactions.

Transactions ensure data integrity: all operations within a transaction are either fully completed or rolled back in case of an error.

An example using sqlite3:

import sqlite3

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

try:
    conn.execute('BEGIN')
    cursor.execute("INSERT INTO users (name) VALUES (?)", ('Alice',))
    cursor.execute("INSERT INTO accounts (user_id, balance) VALUES (?, ?)" , (cursor.lastrowid, 100))
    conn.commit()
except Exception as e:
    conn.rollback()
    print(f"Error: {e}")
finally:
    conn.close()

In this example, if one of the insert operations fails, all changes will be rolled back.