Open connection and begin transaction : Transaction SqlConnection « ADO.net Database « ASP.Net






Open connection and begin transaction

<%@ Page Language="C#" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server">

SqlTransaction _Transact;

void page_load(Object Sender, EventArgs E)
{
    
  String ConnectionString = "Server=localhost; Database=pubs; uid=sa; pwd=;";
  String CommandText = "UPDATE authors SET state='PU' WHERE state='UT'";
  String CommandText2 = "UPDATE authors SET au_id='1' WHERE au_id='2'";
    
    SqlConnection _Connection = new SqlConnection(ConnectionString);
    SqlCommand _Command = new SqlCommand();
    
    try{
        _Connection.Open();
        _Transact = _Connection.BeginTransaction();
        
        _Command.Connection = _Connection;
        _Command.Transaction = _Transact;
        
        _Command.CommandText = CommandText;
        _Command.ExecuteNonQuery();
        
        _Command.CommandText = CommandText2;
        _Command.ExecuteNonQuery();
        
        _Transact.Commit();
        
        MessageLiteralControl.Text = "Transaction Successful!";
    }catch (Exception Err){
        _Transact.Rollback();
        MessageLiteralControl.Text = "Transaction Failed!<br/>" + Err.Message;
    }
    finally{
    _Connection.Close();
    }
}
</script>
<html>
  <body>
    <form runat="server" ID="Form1">
      <p>
        <asp:Label id="MessageLabel" runat="server" EnableViewState="false"></asp:Label>
      </p>
    </form>
  </body>
</html>

 








Related examples in the same category

1.Working with Transactions with an SQL Server Database
2.Implicit Transactions using TransactionScope
3.Using Explicit Transactions using CommittableTransaction