Junior — Middle
Can you explain what the ACID principle is in the context of database transactions?
sobes.tech AI
Answer from AI
The ACID principle describes four key properties of transactions in databases that ensure reliability and data integrity:
- Atomicity — a transaction is completed in full or not at all. If something goes wrong, all changes are rolled back.
- Consistency — after a transaction, the database remains in a correct state, satisfying all rules and constraints.
- Isolation — concurrent transactions do not affect each other, as if they were executed sequentially.
- Durability — after a transaction is committed, changes are saved in the database even in case of failures.
Example in Python using transactions in 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() # Roll back changes in case of error
print('Error:', e)
finally:
conn.close()
Here, either both queries are executed, or none, which corresponds to the principle of atomicity.