我們一直使用C#和mysql與.net連接器,但個別提交有時無法提交所有內容。所以我們現在轉向支持分佈式事務的這個工具http://www.devart.com/dotconnect/mysql/。所有的工作都很好,只是我們不太清楚如何放置多重連接。方法1是將每個連接嵌套到另一箇中。方法2是分開的。我們應該關閉連接或由transScope.Complete()處理;和transScope.Dispose();Devart Connectory使用事務範圍的正確方法Mysql
方法1.
using (TransactionScope transScope = new TransactionScope())
{
string myConnStringLocal = "User Id=***;Password=****;Host=" + globalSettings.settingLocalIP + ";Database=" + globalSettings.settingLocalDB;
using (MySqlConnection connectionLocal = new MySqlConnection(myConnStringLocal))
{
connectionLocal.open()
string myConnStringCentral = "User Id=***;Password=*****;Host=" + globalSettings.settingCentralIP + ";Database=" + globalSettings.settingCentralDB;
using (MySqlConnection connectionCentral = new MySqlConnection(myConnStringCentral))
{
connectionCentral.Open();
string myConnStringCentralCopy = "User Id=*****;Password=*****;Host=" + globalSettings.settingCentralCopyIP + ";Database=" + globalSettings.settingCentralCopyDB;
using (MySqlConnection connectionCentralCopy = new MySqlConnection(myConnStringCentralCopy))
{
connectionCentralCopy.Open();
}
}
}
if (rollbackBoolean == 0)
transScope.Complete();
else
transScope.Dispose();
}
方法2
using (TransactionScope transScope = new TransactionScope())
{
string myConnStringLocal = "User Id=***;Password=****;Host=" + globalSettings.settingLocalIP + ";Database=" + globalSettings.settingLocalDB;
using (MySqlConnection connectionLocal = new MySqlConnection(myConnStringLocal))
{
connectionLocal.open()
}
string myConnStringCentral = "User Id=***;Password=*****;Host=" + globalSettings.settingCentralIP + ";Database=" + globalSettings.settingCentralDB;
using (MySqlConnection connectionCentral = new MySqlConnection(myConnStringCentral))
{
connectionCentral.Open();
}
string myConnStringCentralCopy = "User Id=*****;Password=*****;Host=" + globalSettings.settingCentralCopyIP + ";Database=" + globalSettings.settingCentralCopyDB;
using (MySqlConnection connectionCentralCopy = new MySqlConnection(myConnStringCentralCopy))
{
connectionCentralCopy.Open();
}
if (rollbackBoolean == 0)
transScope.Complete();
else
transScope.Dispose();
}
你爲什麼要開到同一數據庫3個連接?連接沒有被'TransactionScope'關閉。你不必調用'trasnsactionScope.Dispose()' - 'using'語句爲你做。 – YK1
分佈式事務是一種開銷,如果您想擴展您的應用程序,將會是一個很大的障礙。儘可能避免它。 – YK1
@ YK1 no是三個不同的dbs 1.globalSettings.settingLocalDB 2.globalSettings.settingCentralDB和3.globalSettings.settingCentralCopyDB。我知道是乏味的,但我沒有選擇,因爲我現場得到更新數據,否則就會出現混亂的觀點。那麼哪種方法使用1或2?如何在transactionscope之後關閉數據庫連接? – new14