c# - 连接突然中断时 ADO.Net 事务的命运

标签 c# transactions ado.net sql-server-2008-r2

考虑下面的示例代码。

如果在第 2 步(即第 2 个命令)时与数据库的连接突然断开,那么即使我们尝试回滚事务也不会回滚,因为没有与数据库的连接服务器。

在这种情况下,数据库服务器端的事务对象会发生什么情况? 会一直处于等待模式吗? 我当我尝试通过 VPN 连接到数据库服务器来在 ADO.Net 中运行长事务时,遇到过这种情况。

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();
}

最佳答案

连接中止将触发任何未决事务的回滚。参见 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

关于c# - 连接突然中断时 ADO.Net 事务的命运,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22580664/

相关文章:

c# - [LINQ]InsertOnSubmit NullReferenceException

java - 在 C++ 和 Java 之间传播 Oracle 事务

entity-framework - 从 Entity Framework 模型构建数据库模式

sql-server - 什么会导致 SqlClient 重用无效连接?

sql - 如何使用内联 SQL 参数化 IN 语句的集合?

c# - 使用 EF 查询的最佳方式

c# - 无法为 Facebook 创建 SSL/TLS 安全通道

c# - Workflow Foundation 4 中的动态数据类型

c# - 如何回滚 Entity Framework 中的事务

Java EE7 回滚事务