CSharp transactions

transactions

Image credit: commons.wikimedia.org

CSharp transactions

CSharp transactions play a vital role in ADO.Net development. Transaction , in simple words, can be defined as the action that needs to be performed in the form of assets movements in or movements out.
Since money is also a part of an asset due to its value for both parties i.e sender and receiver.
The movements about sending and receiving are called Transactions
The transactions, which are used in CSharp, allows us to operate on number of SQL statements and we may
abort transaction whenever there is an error in one of the sql statements. Lets see it in an example:

This is our web.config file

    <?xml version=”1.0″?>
    <configuration>
    <connectionStrings>
    <add name=”MyConnection” connectionString=”Data Source=ABC;Initial Catalog=XYZ;Integrated Security=True”/>
    </connectionStrings/>
    </configuration>

// this is our code file
using System;
using System.Data.SqlClient;
using System.Diagnostics;
namespace ADOTransaction
{

public class TransactionClass
{
public void TransactionTest()
{
SqlConnection con = new SqlConnection(“ConfigurationManager.ConnectionStrings[“MyConnection”].ConnectionString;”);
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText =”INSERT INTO MyTable(ID, Name) VALUES(@ID, @Name)”;
connection.Open();
SqlTransaction MyTransaction = connection.BeginTransaction();
try
{
cmd.Transaction = MyTransaction;
cmd.Parameters.AddWithValue(“@ID”,1234 );
cmd.Parameters.AddWithValue(“@Name”, “Adeel”);
cmd.ExecuteNonQuery();
// If the command executes perfectly, then the transaction succeeds
MyTransaction.Commit();
}
catch (Exception ex) // catch the error
{
Trace.WriteLine(ex.Message); // write error on trace
MyTransaction.Rollback(); // Abort all the actions performed in the above executed transactions
}
finally
{
// don’t forget to close the connection
con.Close();
}
}
}
}

Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.
Syed Adeel Ahmed on FacebookSyed Adeel Ahmed on GoogleSyed Adeel Ahmed on InstagramSyed Adeel Ahmed on Twitter

Published by

Syed Adeel Ahmed

Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.