使用单个事务(多个连接字符串)将数据保存在多个数据库中
本文关键字:数据 保存 数据库 存在 连接 单个 事务 字符串 | 更新日期: 2023-09-27 18:26:09
我有一个带有多个数据库的服务器,每个数据库将使用不同的用户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.
除此之外的任何其他解决方案都将受到高度赞赏。
必须使用from 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服务,在收件人数据库