Sobes.tech
Junior — Middle

Can you explain the main properties of transactions in databases related to ACID principles?

sobes.tech AI

Answer from AI

ACID is a set of properties that guarantee reliable transactions in databases:

  • Atomicity: the transaction is completed in full or not at all. If something goes wrong, all changes are rolled back.
  • Consistency: after the transaction completes, the database remains in a correct state, satisfying all rules and constraints.
  • Isolation: parallel transactions do not affect each other, as if they were executed sequentially.
  • Durability: after a transaction is committed, changes are saved and not lost even in case of failures.

Example in Python using SQLite and a context manager for transactions:

import sqlite3

conn = sqlite3.connect('example.db')
try:
    with conn:
        conn.execute("INSERT INTO users (name) VALUES (?)", ('Alice',))
        conn.execute("INSERT INTO accounts (user, balance) VALUES (?, ?)" , ('Alice', 100))
except sqlite3.Error as e:
    print(f"Transaction error: {e}")

Here, with conn: guarantees atomicity: if one of the operations fails, the changes are not saved.