A transaction is a single unit of work which means either run ALL query or NONE. If a transaction is successful, then all of the data that we want to store on database are committed. If a transaction encounters errors/exceptions and must be canceled or rolled back
protected void btnSave_Click(object sender, EventArgs e)
{
bool check_value = false;
ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
using (SqlConnection objConn = new SqlConnection(ConStr))
{
objConn.Open();
SqlCommand cmd = objConn.CreateCommand();
SqlTransaction trans;
trans = objConn.BeginTransaction();
cmd.Connection = objConn;
cmd.Transaction = trans;
try
{
cmd.CommandText = @"Insert into tbl_student_personal_details(s_id,name,address) values('101','raj','raipur')";
cmd.ExecuteNonQuery();
cmd.CommandText = "Insert into tbl_student_educational_details(s_id,education,job) values('101','BE','software developer')";
cmd.ExecuteNonQuery();
//you can run multiple query
//when all query run successfully then commit
trans.Commit();
check_value = true;
}
catch (Exception ex)
{
//if qury failed then rollback
trans.Rollback();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('Something Went Wrong')", true);
}
finally
{
objConn.Close();
if (check_value == true)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('Data save Successfully')", true););
}
}
}
}