In database management, transactions are essential to ensure data integrity and consistency. A transaction is a sequence of operations performed as a single logical unit of work. Transactions are crucial because they guarantee that all operations within the transaction are completed successfully before committing the changes to the database. If any operation fails, the entire transaction can be rolled back, leaving the database in its original state.
Implementing Transactions to Ensure Data Integrity
What is a Transaction?
A transaction is a unit of work that is performed against a database. It is a sequence of operations performed as a single logical unit of work. A transaction has the following properties, often referred to as ACID properties.
- Atomicity: Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state.
- Consistency: Ensures that the database properly changes states upon a successfully committed transaction.
- Isolation: Enables transactions to operate independently of and transparent to each other.
- Durability: Ensures that the result or effect of a committed transaction persists in case of a system failure.
Implementing Transactions in ADO.NET
In ADO.NET, transactions are managed using the SqlTransaction class, which is part of the System.Data.SqlClient namespace. Below is a basic example of how to implement a transaction in ADO.NET.
using System;
using System.Data;
using System.Data.SqlClient;
namespace AdoNetTransactionExample
{
class Program
{
static void Main(string[] args)
{
string connectionString = "your_connection_string_here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
try
{
SqlCommand command1 = connection.CreateCommand();
command1.Transaction = transaction;
command1.CommandText = "INSERT INTO Table1 (Column1) VALUES ('Value1')";
command1.ExecuteNonQuery();
SqlCommand command2 = connection.CreateCommand();
command2.Transaction = transaction;
command2.CommandText = "INSERT INTO Table2 (Column1) VALUES ('Value2')";
command2.ExecuteNonQuery();
// Commit the transaction
transaction.Commit();
Console.WriteLine("Both records were written to the database.");
}
catch (Exception ex)
{
// Rollback the transaction if any command fails
try
{
transaction.Rollback();
}
catch (Exception rollbackEx)
{
Console.WriteLine("Rollback Exception: " + rollbackEx.Message);
}
Console.WriteLine("Exception: " + ex.Message);
}
}
}
}
}

Join the conversation! Your thoughts help the community grow.