Fate of an ADO.Net Transaction when connection is suddenly broken

久未见 提交于 2020-02-15 08:30:42

问题


Consider the sample code below.

If the connection to the database is suddenly broken when on STEP 2 (i.e. 2nd command), then even if we try to rollback the transaction it will not rollback since there is no connection to the database server.

In such a case, what happens to the transaction object on the database server side? Will it remain in a waiting mode? I have had this situation come up when I tried to run a long transaction in ADO.Net by connecting to database servers through a VPN connection.

using (SqlConnection connection =
        new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction = null;

try
{
    // BeginTransaction() Requires Open Connection
    connection.Open();

    transaction = connection.BeginTransaction();

    // Assign Transaction to Command
    command.Transaction = transaction;

    // Execute 1st Command
    command.CommandText = "Insert ...";
    command.ExecuteNonQuery();

    // Execute 2nd Command
    command.CommandText = "Update...";
    command.ExecuteNonQuery();

    transaction.Commit();
}
catch
{
    transaction.Rollback();
    throw;
}
finally
{
    connection.Close();
}

}


回答1:


A connection abort will trigger rollback of any pending transaction. See Controlling Transactions:

If the client's network connection to an instance of the Database Engine is broken, any outstanding transactions for the connection are rolled back when the network notifies the instance of the break



来源:https://stackoverflow.com/questions/22580664/fate-of-an-ado-net-transaction-when-connection-is-suddenly-broken

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!