【问题标题】:Save data in multiple databases using a single transaction (multiple connection strings)使用单个事务(多个连接字符串)将数据保存在多个数据库中
【发布时间】:2014-10-10 21:06:04
【问题描述】:

我有一个带有多个数据库的服务器,每个数据库将使用不同的用户 ID pswd 连接。 我需要更新/插入/删除任何数据库中表中的记录。如果发生任何错误 - 将所有更改回滚到当前事务中的所有数据库。

我的代码如下:

string connStrTest1 = "connectionstring to connect to DB1";
string connStrTest2 = "connectionstring to connect to DB2";
string connStrTest3 = "connectionstring to connect to DB3";

//For an example I have created 3 DBs which have the same tables and columns.

string InsertPerson = "insert into Person (Id, Name, City) VALUES (123, 'Jon' , 'England' )";
string InsertPhones = "insert into Phones (Id, Number, SrvcPrvdr) VALUES (123, '+442345678' , 'Some')";
string InsertWork = "INSERT INTO WorkPlace (Id, Office, Address) VALUES (123, 'Soem', 'England' )";
string FailInsertWork = "INSERT INTO WorkPlace (Id, Office, Address) VALUES (999, 'some', 'Australia' )";


static void Main()
{
    using (var connTest1 = new SqlConnection(connStrTest1))
    {
        connTest1.Open();
        var transaction = connTest1.BeginTransaction();
        try
        {
            //Update 1st DB here.....
            var command = new SqlCommand(InsertPerson, connTest1, transaction);
            command.CommandType = System.Data.CommandType.Text;
            command.CommandText = InsertPerson;
            command.ExecuteNonQuery();

            command.CommandText = InsertPhones;
            command.ExecuteNonQuery();

            command.CommandText = InsertWork;
            command.ExecuteNonQuery();

            //updating DBs 2 & 3 here
            updateRecords();

            transaction.Commit();
        }
        catch (Exception ex)
        {
            transaction.Rollback();
            throw ex;
        }
    }
}


private static void updateRecords()
{
    //Updating tables in 2nd Test DB
    using (var conn = new SqlConnection(connStrTest2))
    {
        conn.Open();
        try
        {
            var command = new SqlCommand(InsertPerson, conn);
            command.CommandType = System.Data.CommandType.Text;
            command.ExecuteNonQuery();

            command.CommandText = InsertPhones;
            command.ExecuteNonQuery();

            command.CommandText = InsertWork;
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    //Updating tables in 3rd Test DB
    using (var conn = new SqlConnection(connStrTest3))
    {
        conn.Open();
        try
        {
            var command = new SqlCommand(InsertPerson, conn);
            command.CommandType = System.Data.CommandType.Text;
            command.ExecuteNonQuery();

            command.CommandText = InsertPhones;
            command.ExecuteNonQuery();

            if (fail)
            {
                command.CommandText = FailInsertWork;
                command.ExecuteNonQuery();
            }
            else
            {
                command.CommandText = InsertWork;
                command.ExecuteNonQuery();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

在查询 FailInsertWork 中,我编写了查询,以便在发生外键冲突时引发异常。

现在,我希望我的程序能够在更新到第三个数据库失败时运行,之前为第一和第二个数据库发生的所有插入也应该回滚。

您可以将 connectionString 或连接实例或事务实例传递给 updateRecords 方法。

仅供参考 - 我不想使用 TransactionScope/DTC/System.Transactions.Transaction。

高度赞赏除此之外的任何其他解决方案。

【问题讨论】:

  • 为什么不想使用 DTC?它专为您的用例而设计。我很好奇你为什么要重新发明轮子。
  • 这正是实现分布式事务/XA 事务的目的。实施您自己的 2PC 系统很容易出错,并且可能永远无法在所有恢复方案中正常工作。

标签: c# sql transactions


【解决方案1】:

您必须从 TransactionScope 使用。 TransactionScope 是 .NET Framework 中一个非常特殊且重要的类。支持来自代码块的事务是该类的主要职责。它易于使用,例如:

// This function takes arguments for 2 connection strings and commands to create a transaction  
// involving two SQL Servers. It returns a value > 0 if the transaction is committed, 0 if the  
// transaction is rolled back. To test this code, you can connect to two different databases  
// on the same server by altering the connection string, or to another 3rd party RDBMS by  
// altering the code in the connection2 code block. 
static public int CreateTransactionScope(
    string connectString1, string connectString2,
    string commandText1, string commandText2)
{
    // Initialize the return value to zero and create a StringWriter to display results. 
    int returnValue = 0;
    System.IO.StringWriter writer = new System.IO.StringWriter();

    try
    {
        // Create the TransactionScope to execute the commands, guaranteeing 
        // that both commands can commit or roll back as a single unit of work. 
        using (TransactionScope scope = new TransactionScope())
        {
            using (SqlConnection connection1 = new SqlConnection(connectString1))
            {
                // Opening the connection automatically enlists it in the  
                // TransactionScope as a lightweight transaction.
                connection1.Open();

                // Create the SqlCommand object and execute the first command.
                SqlCommand command1 = new SqlCommand(commandText1, connection1);
                returnValue = command1.ExecuteNonQuery();
                writer.WriteLine("Rows to be affected by command1: {0}", returnValue);

                // If you get here, this means that command1 succeeded. By nesting 
                // the using block for connection2 inside that of connection1, you 
                // conserve server and network resources as connection2 is opened 
                // only when there is a chance that the transaction can commit.    
                using (SqlConnection connection2 = new SqlConnection(connectString2))
                {
                    // The transaction is escalated to a full distributed 
                    // transaction when connection2 is opened.
                    connection2.Open();

                    // Execute the second command in the second database.
                    returnValue = 0;
                    SqlCommand command2 = new SqlCommand(commandText2, connection2);
                    returnValue = command2.ExecuteNonQuery();
                    writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
                }
            }

            // The Complete method commits the transaction. If an exception has been thrown, 
            // Complete is not  called and the transaction is rolled back.
            scope.Complete();

        }

    }
    catch (TransactionAbortedException ex)
    {
        writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
    }
    catch (ApplicationException ex)
    {
        writer.WriteLine("ApplicationException Message: {0}", ex.Message);
    }

    // Display messages.
    Console.WriteLine(writer.ToString());

    return returnValue;
}

在MSDN上查看这个

【讨论】:

  • 这个例子有一个严重的缺陷。它将使用可序列化的事务级别,这很容易出现死锁问题。
【解决方案2】:

如果我理解正确,您正试图让您的 .net 代码管理多个收件人数据库。

一种方法是切换到 .Net 生成的 ID。我建议guid。

然后创建一个管理数据库,以便在应用程序中断时修复/更正收件人数据库。

事务信息应在针对接收方数据库执行之前插入到管理数据库中,并应在所有数据库成功执行事务后删除。您甚至可以为每个数据库放置一个位列。

如果发生中断,您只需检查管理数据库中已启动的事务并决定如何更正不完整的事务。

根据管理数据库的健壮程度,您甚至可以创建一个 Windows 服务,该服务可以在 recipient database 恢复联机后赶上它。 p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多