本機交易通常使用在主、從式應用程式中,更新的對象限定於同一個資料來源。應用程式可以使用在ADO.NET當中的Connection物件搭配Transaction物件來完成,而Command物件有一個Transaction屬性,允許把想要執行的多個命令,包裝成一個單獨的交易。讓整個交易中所有的工作,都有一致的結果,不是完全成功執行就是完全失敗。 connectionString="Data Source=localhost;Initial Catalog=Northwind;User ID=sa; Password=P@$sW0rD; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />public class Trans { private SqlConnection m_Connection = new SqlConnection(Properties.Settings.Default.NorthwindConStr); private string _ErrorStr; public string ErrorStr { get { return this._ErrorStr; } set { this._ErrorStr = value; } } public bool Transact() { bool result = false; SqlTransaction tx = null; string cmdstr1 = @"UPDATE dbo.Products SET UnitPrice = UnitPrice*1.2"; string cmdstr2 = @"UPDATE Production.Product SET ListPrice = ListPrice*1.2"; try { m_Connection.Open(); tx = m_Connection.BeginTransaction(); SqlCommand cmd1 = new SqlCommand(cmdstr1, m_Connection, tx); SqlCommand cmd2 = new SqlCommand(cmdstr2, m_Connection, tx); cmd1.ExecuteNonQuery(); m_Connection.ChangeDatabase("AdventureWorks"); cmd2.ExecuteNonQuery(); tx.Commit(); result = true; } catch (SqlException sqlex) { this.ErrorStr = sqlex.Message.ToString(); tx.Rollback(); } finally { m_Connection.Close(); } return result; }}
標籤: ADO.NET
較新的文章 較舊的文章 首頁