Transactions are used to execute the sequence of operations (to execute one operation after another).
If an error occurs during the execution of an operation, then all previous operations are rolled back (canceled).
That is, either all operations will be performed without errors or no operations will be performed (if at least one error has occurred).
Transaction Management:
C#
Write the code in the file Program.cs
using System;
// for SQL ADO.NET
using Microsoft.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// connection string
string connectionString = @"Data Source=EVGENI;Initial Catalog=MyDatabase1;Integrated Security=True";
// connect to db
using (SqlConnection connection = new SqlConnection(connectionString))
{
// open db
connection.Open();
// Creating a Transaction
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
try
{
// Operation 1
command.CommandText = "INSERT INTO Books (Name, Price) VALUES('На море', 120)";
command.ExecuteNonQuery();
// Operation 2
command.CommandText = "INSERT INTO Books (Name, Price) VALUES('Читаем книгу', 230)";
command.ExecuteNonQuery();
// Completing the Transaction
transaction.Commit();
}
catch (Exception ex)
{
// Canceling a Transaction
transaction.Rollback();
}
}
}
}
}