Junior — Middle
Explain what transactions are in a database management system and their main properties.
sobes.tech AI
Answer from AI
A transaction in a database management system (DBMS) is a sequence of operations that are executed as a single unit. The main idea is that either all operations of the transaction are successfully completed, or none are applied (atomicity).
The key properties of transactions are described by the acronym ACID:
- Atomicity: the transaction is completed in full or not at all.
- Consistency: after the transaction completes, the database remains in a correct state, satisfying all constraints.
- Isolation: concurrent transactions do not affect each other, resulting in outcomes as if they were executed sequentially.
- Durability: after a commit, changes are saved even in case of system failures.
Example in C# using transactions in ADO.NET:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
try
{
var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "INSERT INTO Accounts (Name, Balance) VALUES ('User1', 1000)";
command.ExecuteNonQuery();
command.CommandText = "UPDATE Accounts SET Balance = Balance - 100 WHERE Name = 'User2'";
command.ExecuteNonQuery();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}