SqlTransaction in C#

Akiii
Posted by Akiii under C# category on | Points: 40 | Views : 4048
I am using SqlTransaction in a button click and using stored procedure to insert in the data in the database.

protected void Button_Click(object sender, EventArgs e)
{
string firstname = txtFirstName.Text;
string lastemail = txtLastName.Text;
string id = txtId.Text;
SqlConnection myConnection = new SqlConnection(Connection_String);
SqlTransaction myTransaction = null;
try
{
myConnection.Open();
myTransaction = myConnection.BeginTransaction();
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Connection = myConnection;
myCommand.CommandText = "insert_data_in_employee_table";
myCommand.Transaction = myTransaction;
SqlParameter Parameter1 = new SqlParameter("@firstname", firstname);
SqlParameter Parameter2 = new SqlParameter("@lastemail", lastemail);
SqlParameter Parameter3 = new SqlParameter("@id", id);
myCommand.Parameters.Add(Parameter1);
myCommand.Parameters.Add(Parameter2);
myCommand.Parameters.Add(Parameter3);
myCommand.ExecuteNonQuery();
myTransaction.Commit();
lblMsg.Text = "Transaction Committed";
}
catch (SqlException ex)
{
myTransaction.Rollback();
lblMsg.Text = "Transaction Rollbacked due to " + ex.Message;
}
finally
{
// Close the connection.
if( myConnection.State == ConnectionState.Open )
{
myConnection.Close();
}
}
}




Thanks and Regards
Akiii

Comments or Responses

Login to post response