Junior — Middle
Can you explain what is meant by transactions in database management systems?
sobes.tech AI
Answer from AI
A transaction in database management systems is a sequence of operations that are executed as a single unit. It has four main properties (ACID):
- Atomicity: all operations of the transaction are completed fully or not at all.
- Consistency: after the transaction completes, the database remains in a correct state.
- Isolation: concurrent transactions do not affect each other.
- Durability: after a transaction is committed, its changes are permanent even in case of failures.
Example in Python using SQLite:
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, balance) VALUES ('Alice', 1000)")
conn.commit() # Commit the transaction
except Exception as e:
conn.rollback() # Rollback in case of error
print('Error:', e)
finally:
conn.close()
Here, both insert operations either execute together or not at all.