繁体   English   中英

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

[英]Save data in multiple databases using a single transaction (multiple connection strings)

我有一台具有多个数据库的服务器,每个数据库将使用不同的用户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中,我编写了查询,以便由于发生外键冲突而将引发异常。

现在,我希望我的程序能够正常运行,因为对第3个DB的更新失败时,以前对第1个和第2个DB进行的所有插入操作也都应回滚。

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

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

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

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

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

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

然后创建一个管理数据库 ,以便您可以在应用程序中断的情况下修复/更正收件人数据库

在对接收者数据库执行事务信息之前,应将事务信息插入管理数据库中 ,一旦所有数据库成功执行了事务,则应将其删除。 您甚至可以为每个数据库放置一列。

万一发生中断,您只需要在管理数据库中检查已启动的事务并决定如何更正未完成的事务。

根据管理数据库的强大程度,您甚至可以创建一个Windows服务,以在收件人数据库重新联机后赶上脱机的收件人数据库

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM