问题
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