Junior — Middle
Have you applied the concept of transactions in your projects or tasks?
sobes.tech AI
Answer from AI
The concept of transactions is widely used in projects where atomicity of operations is important — that is, either all actions are successfully completed or the system reverts to its original state.
In Python, transactions are often used when working with databases through ORM or drivers that support transactions. For example, when working with sqlite3 or SQLAlchemy, you can wrap multiple operations in a transaction to avoid partial data updates in case of errors.
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 (last_insert_rowid(), 1000)")
conn.commit() # Confirm the transaction
except Exception as e:
conn.rollback() # Roll back changes in case of error
print(f"Error: {e}")
finally:
conn.close()
Thus, transactions help ensure data integrity and correctness of business logic in applications.