Transaction in .NETTransaction is a process. A transaction can be a set of more then one process. If a transaction is a set of more then one process, then for successful completion of that transaction, it is necessary that all processes should be executed successfully in that transaction.
Let understand the transaction concept with this example.
Here in this example, I am using a set of two process transaction. Here I am executing two commands simultaneously with transaction. With first command I am deleting a record from table and with second I am inserting a new record in the table.
Before executing the transaction, the record in the table are:
Figure 1: Here in transaction I am deleting the record where location is England and also I am inserting a record in the table.
The code for this transaction is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace TranSactionIn.NET
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con;
SqlCommand cmd1=new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
SqlTransaction trm;
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=MCN0100;Initial Catalog=Employee; Uid=sa; pwd=");
cmd1.CommandText = "delete from EmployeeRecord where Location='England'";
cmd2.CommandText = "Insert into EmployeeRecord (DeptNo,Name,DepartName,Location) values ('901','Sahib','Manager','Africa')";
cmd1.Connection = con;
cmd2.Connection = con;
con.Open();
trm = con.BeginTransaction();
cmd1.Transaction = trm;
cmd2.Transaction = trm;
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
trm.Commit();
}
}
}
After running this code in table data we see that all records deleted where Location was England and a new record has been inserted in table. A very good example of transaction is banking money transaction.
Figure 2: After Transaction commit we can see the changed record.