How to Use Transaction Asp.net Project ?


If we are doing two or more tasks with database, then we should have to use transaction to ensure the task had been completed successfully.

There are two methods to do this task.

  1. Using Store procedure in database
  2. Using C# code.

Syntax for transaction in store procedure ,please refer by old post

https://chandradev819.wordpress.com/2010/10/24/try-catch-syntax-in-store-procedure/

Using C# code

Ado.net 2.0 and later vesion support transaction feature.

We can write code like this.

 

using (SqlConnection connection =

new SqlConnection(connectionString))

{

using (SqlCommand command =

connection.CreateCommand())

{

SqlTransaction transaction = null;

try

{

// BeginTransaction() Requires Open Connection

connection.Open();

transaction = connection.BeginTransaction();

// Assign Transaction to Command

command.Transaction = transaction;

// Execute 1st Command

command.CommandText = “Insert …”;

command.ExecuteNonQuery();

// Execute 2nd Command

command.CommandText = “Update…”;

command.ExecuteNonQuery();

transaction.Commit();

}

catch

{

transaction.Rollback();

throw;

}

finally

{

connection.Close();

}

}

}

Advertisement

2 thoughts on “How to Use Transaction Asp.net Project ?

  1. Smithc126 April 29, 2014 / 12:25 am

    I truly appreciate this article.Really thank you! Fantastic. cbdddaddkkgadeae

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.