Commit Method
Collapse the table of content
Expand the table of content

IDbTransaction.Commit Method ()


Commits the database transaction.

Namespace:   System.Data
Assembly:  System.Data (in System.Data.dll)

void Commit()

Exception Condition

An error occurred while trying to commit the transaction.


The transaction has already been committed or rolled back.


The connection is broken.

The following example creates instances of the derived classes, SqlConnection and a SqlTransaction. It also demonstrates how to use the Commit, BeginTransaction, and Rollback methods.

private static void ExecuteSqlTransaction(string connectionString)
    using (SqlConnection connection = new SqlConnection(connectionString))

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";

            // Attempt to commit the transaction.
            Console.WriteLine("Both records are written to database.");
        catch (Exception ex)
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            catch (Exception ex2)
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);

.NET Framework
Available since 1.1
Return to top
© 2015 Microsoft