我的系統在同一個MySql中有2個數據庫。業務是確保數據在同一事務中完全插入到2個數據庫中。下面是我的示例:C#MySql TransactionScope
public void test()
{
int returnValue = 0;
System.IO.StringWriter writer = new System.IO.StringWriter();
try
{
using (TransactionScope scope = new TransactionScope())
{
returnValue = TestA(returnValue, writer);
returnValue = TestB(returnValue, writer);
scope.Complete();
}
}
catch (Exception ex)
{
}
}
private static int TestB(int returnValue, System.IO.StringWriter writer)
{
using (MySqlConnection connection2 = new MySqlConnection("server=localhost;database=test;user id=root;password=root;port=3307;characterset=utf8;connectiontimeout=72000;"))
{
connection2.Open();
// Execute the second command in the second database.
returnValue = 0;
MySqlCommand command2 = new MySqlCommand("Insert tbb (`time`)value ('10:00:00')", connection2);
returnValue = command2.ExecuteNonQuery();
writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
}
return returnValue;
}
private static int TestA(int returnValue, System.IO.StringWriter writer)
{
using (MySqlConnection connection1 = new MySqlConnection("server=localhost;database=test1;user id=root;password=root;port=3307;characterset=utf8;connectiontimeout=72000;"))
{
connection1.Open();
// Create the SqlCommand object and execute the first command.
MySqlCommand command1 = new MySqlCommand("Insert tb1 (`Name`, `Value`)value ('ai', '2017-04-26')", connection1);
returnValue = command1.ExecuteNonQuery();
writer.WriteLine("Rows to be affected by command1: {0}", returnValue);
}
return returnValue;
}
當我跑,我得到了錯誤:
Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported.
它爲什麼會發生?
如果無法修復,請給我其他解決方案。
錯誤很明顯。它不被支持。您可以嘗試只使用1個連接,然後在第二個查詢中插入「test1..tb1」 – user5328504
請給我其他人的解決方案 –
基本上,兩個連接同時使用相同的服務器實例,而不關閉以前的連接,這會導致併發問題。解決方法是爲每個連接使用不同的'TransactionScope'(完成每個事務後使用'Complete'方法)幷包含'AutoEnlist = false'。 –