To give you an example of commit and rollback transaction, take a look at the following code.
1. The program will insert a record to tblLogs table (Logs).
2. Then insert a new category to tblCategories table (Category).
3. If insertion to category failed, rollback the 1st command (which is insert to tblLogs) else apply the changes by committing the transaction.
How to Commit and Rollback SQL Transaction in C#
using (SqlConnection con = new SqlConnection("Data Source=mnlho8ap33;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678"))
{
using (SqlCommand cmd = con.CreateCommand())
{
SqlTransaction trans = null;
try
{
con.Open();
// BeginTransaction() Requires Open Connection
trans = con.BeginTransaction();
// Assign Transaction to Command
cmd.Transaction = trans;
//1st command to execute. This will be rollback if 2nd command fails
cmd.CommandText = "INSERT INTO tblLogs (LogDescription) VALUES ('Inserted New Category')";
cmd.ExecuteNonQuery();
//2nd command to execute
cmd.CommandText = "INSERT INTO tblCategories (CategoryName) VALUES ('TEST CATEGORY')";
cmd.ExecuteNonQuery();
trans.Commit();
}
catch
{
trans.Rollback();
Console.WriteLine("Error while processing command. Previous execution was rollback");
}
finally
{
con.Close();
}
}
}
How to Commit and Rollback SQL Transaction in VB.NET
Dim con As New SqlConnection("Data Source=mnlho8ap33;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678")
Dim cmd As SqlCommand = con.CreateCommand()
Dim trans As SqlTransaction = Nothing
Try
con.Open()
'BeginTransaction() Requires Open Connection
trans = con.BeginTransaction()
'Assign Transaction to Command
cmd.Transaction = trans
'1st command to execute. This will be rollback if 2nd command fails
cmd.CommandText = "INSERT INTO tblLogs (LogDescription) VALUES ('Inserted New Category')"
cmd.ExecuteNonQuery()
'2nd command to execute
cmd.CommandText = "INSERT INTO tblCategories (CategoryName) VALUES ('TEST CATEGORY')"
cmd.ExecuteNonQuery()
trans.Commit()
Catch
trans.Rollback()
Console.WriteLine("Error while processing command. Previous execution was rollback")
Finally
con.Close()
End Try
Don't forget to include System.Data.SqlClient namespace.
For more coding tips & tricks, subscribe now.
1 comments:
Hello
I have taken many procedures ,i want to rollback them in case any error came in any of them.
How it'll possible .Please explain with example with multiple procedures
Thanks in Advance
Post a Comment