Sobes.tech
Junior — Middle

Explain what is meant by a transaction in the context of working with a database

sobes.tech AI

Answer from AI

A transaction in database management is a sequence of operations that are executed as a single unit. It has four main properties (ACID): atomicity, consistency, isolation, and durability.

  • Atomicity: all operations within a transaction are either fully completed or not executed at all.
  • Consistency: a transaction transforms the database from one correct state to another.
  • 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 Java using JDBC:

Connection conn = dataSource.getConnection();
try {
    conn.setAutoCommit(false); // Start transaction

    // Perform multiple operations
    PreparedStatement ps1 = conn.prepareStatement("INSERT INTO users(name) VALUES (?)");
    ps1.setString(1, "Ivan");
    ps1.executeUpdate();

    PreparedStatement ps2 = conn.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE user_id = ?");
    ps2.setBigDecimal(1, new BigDecimal("100.00"));
    ps2.setInt(2, 1);
    ps2.executeUpdate();

    conn.commit(); // Commit transaction
} catch (SQLException e) {
    conn.rollback(); // Rollback transaction on error
} finally {
    conn.setAutoCommit(true);
    conn.close();
}

Thus, a transaction ensures data integrity when performing multiple related operations.

Explain what is meant by a transaction in the context… - sobes.tech