Tuesday, April 8, 2014

Transaction Control in ADO.NET


Transaction Control is used when  we want that the transaction is updated or commit in Database only when it is completed properly other wise rollback it.




here is the code for that:---

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication111

{
 
public partial class Form1 : Form
{
 
public Form1()
{
InitializeComponent();
}
 
SqlConnection con = new SqlConnection(@"Data Source=-SIR\Raj;Initial Catalog=MultiDB;Integrated Security=True");
SqlCommand cmd,cmd1;
SqlTransaction tran;

private void button1_Click(object sender, EventArgs e)
{
con.Open();
tran = con.BeginTransaction();
 
cmd=new SqlCommand("UPDATE Account SET Amount=Amount-"+textBox2.Text+" WHERE Acc_no="+textBox1.Text+"",con);
cmd1=new SqlCommand("UPDATE Account SET Amount=Amount+"+textBox2.Text+" WHERE Acc_no="+textBox3.Text+"",con);
cmd.Transaction = tran;
cmd1.Transaction = tran;
 
int x = cmd.ExecuteNonQuery();
int y = cmd1.ExecuteNonQuery();
if (x > 0 && y > 0)
{
tran.Commit();
 
MessageBox.Show("Transaction Ho gaya");
}
  else
{
tran.Rollback();
 
MessageBox.Show("Transaction nahi Ho sakta");
}
con.Close();
}
}
}
 
 

No comments:

Post a Comment