How to use transaction concept in c#
In this article am going to explain what is transaction and how to implement it with an example of banking transaction concept.
In this example I used windows application with access database for storing bank account numbers and balance in that accounts.
Transaction:
*Transaction is concept of executing a set of DML(Data Manipulation Language) statements at same time.
*If we want more than one DML statements to execute at a time then we need transaction.
*If all statements of transaction are executed successfully then it should call commit method even one statement is failed then it should call rollback method.
*For transaction implementation we have class called OleDbTransaction (for oledb).
Open access data base and create bank table
Accountno amount
1001 20000
1002 30000
Create new windows forms application
*Drag and drop 3 labels, 3 textboxes and 2 button controls.
*Design of form is below
*Go to Form1.cs and write the below code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace transaction
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E://srid documents/mydocsssssss/products.accdb;User ID=admin");
void clear()
{
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(TextBox))
{
((TextBox)(c)).Text = string.Empty;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
clear();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string s1 = "update bank set amount=amount-" + textBox3.Text + "
where accountno=" + textBox1.Text;
string s2 = "update bank set amount=amount+" + textBox3.Text + "
where accountno=" + textBox2.Text;
cn.Open();
OleDbTransaction tran = cn.BeginTransaction();
OleDbCommand cmd = new OleDbCommand(s1, cn, tran);
int x = cmd.ExecuteNonQuery();
OleDbCommand cmd2 = new OleDbCommand(s2, cn, tran);
int y = cmd2.ExecuteNonQuery();
if (x == 0 || y == 0)
{
tran.Rollback();
MessageBox.Show("Your Transaction failed...!");
clear();
textBox1.Focus();
}
else
{
tran.Commit();
MessageBox.Show("Your Transaction is succesfull...!");
clear();
textBox1.Focus();
}
}
}
}
*Press control+F5 and run the application
Please visit my article in the given below not only inline query i had given for sqlBulkcopy
http://www.dotnetspider.com/resources/45420-Database-transactions-How-Use-Database-Transactions.aspx