使用单个事务(多个连接字符串)将数据保存在多个数据库中

时间:2014-10-10 21:06:04

标签: c# sql transactions

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

我的代码如下所示:

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中,我编写了查询,以便在发生外键冲突时引发异常。

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

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

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

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

2 个答案:

答案 0 :(得分:4)

您必须使用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

上查看此内容

答案 1 :(得分:0)

如果我理解正确,您尝试使.net代码管理多个收件人数据库

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

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

交易信息应在管理数据库中插入收件人数据库之前插入管理数据库,并应在所有数据库成功执行交易后删除。您甚至可以为每个数据库放置一个位列。

如果发生中断,您只需检查管理数据库中的已启动交易,并确定如何更正未完成的交易。

根据管理数据库的强大程度,您甚至可以创建一个Windows服务来捕获收件人数据库,该服务一旦重新联机就会脱机。