dotConnect for SQL Server Documentation
Devart.Data.SqlServer Namespace / SqlTransaction Class / Commit Method
Example

In This Topic
    Commit Method
    In This Topic
    Commits the database transaction.
    Syntax
    'Declaration
     
    Public Overrides Sub Commit() 
    public override void Commit()
    Remarks
    The Commit method is equivalent to the SQL COMMIT statement.
    Example
    The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods.
    public void RunSqlTransaction(string myConnString)
    {
      SqlConnection myConnection = new SqlConnection(myConnString);
      myConnection.Open();
    
      SqlCommand myCommand = new SqlCommand();
      SqlTransaction myTrans;
    
      // Start a local transaction
      myTrans = myConnection.BeginTransaction();
      // Assign transaction object for a pending local transaction
      myCommand.Transaction = myTrans;
    
      try
      {
        myCommand.CommandText = "INSERT INTO Test.Dept(DeptNo, DName) Values(50, 'DEVELOPMENT')";
        myCommand.ExecuteNonQuery();
        myCommand.CommandText = "INSERT INTO Test.Dept(DeptNo, DName) Values(60, 'PRODUCTION')";
        myCommand.ExecuteNonQuery();
        myTrans.Commit();
        Console.WriteLine("Both records are written to database.");
      }
      catch(Exception e)
      {
        myTrans.Rollback();
        Console.WriteLine(e.ToString());
        Console.WriteLine("Neither record was written to database.");
      }
      finally
      {
        myConnection.Close();
      }
    }
    Public Sub RunSqlTransaction(myConnString As String)
      Dim myConnection As New SqlConnection(myConnString)
      myConnection.Open()
    
      Dim myCommand As New SqlCommand()
      Dim myTrans As SqlTransaction
    
      ' Start a local transaction
      myTrans = myConnection.BeginTransaction()
      ' Assign transaction object for a pending local transaction
      myCommand.Transaction = myTrans
    
      Try
        myCommand.CommandText = "INSERT INTO Test.Dept(DeptNo, DName) Values(50, 'DEVELOPMENT')"
        myCommand.ExecuteNonQuery()
        myCommand.CommandText = "INSERT INTO Test.Dept(DeptNo, DName) Values(60, 'PRODUCTION')"
        myCommand.ExecuteNonQuery()
        myTrans.Commit()
        Console.WriteLine("Both records are written to database.")
      Catch e As Exception
        myTrans.Rollback()
        Console.WriteLine(e.ToString())
        Console.WriteLine("Neither record was written to database.")
      Finally
        myConnection.Close()
      End Try
    End Sub
    Requirements

    Target Platforms: Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

    See Also