多資料庫交易處理[改寫]

來源:互聯網
上載者:User
看見園子裡面一位高人寫了一篇多資料庫交易處理的東西,覺得很有意思,把它重寫了一下。

在一個資料庫中實現事務是沒什麼問題,當時項目中常常會遇到多個資料庫交叉事務的情況,這個方法使用兩個SqlTransaction 來處理這兩個資料庫中的事務,當一個更新不成功兩個都要復原。

public void TransactionDebug()
  {

   string sql1 = @"Data Source=XXXXXX;Initial Catalog=stuDB;Integrated Security=True";
   string sql2 = @"Data Source=XXXXXX;Initial Catalog=Northwind;Integrated Security=True";

   SqlConnection conn1 = new SqlConnection(sql1);
   SqlConnection conn2 = new SqlConnection(sql2);

   string sqlUpdate1 = "UPDATE stuInfo SET stuAddress='江南' WHERE stuNO='s25301'";
   string sqlUpdate2 = "UPDATE Products SET ProductName='Chian' WHERE ProductID=1";

   SqlCommand sc1 = new SqlCommand(sqlUpdate1, conn1);
   SqlCommand sc2 = new SqlCommand(sqlUpdate2, conn2);

   conn1.Open();
   SqlTransaction sqlTran1 = conn1.BeginTransaction();
   conn2.Open();
   SqlTransaction sqlTran2 = conn2.BeginTransaction();

   int effectrow=0;

   using(TransactionScope tranScope = new TransactionScope())
   {
    try
    {
     sc1.Transaction = sqlTran1;
     effectrow += sc1.ExecuteNonQuery();

     sc2.Transaction = sqlTran2;
     effectrow += sc2.ExecuteNonQuery();
    }
    catch(SqlException ex)
    {
     sqlTran1.Rollback();
     sqlTran2.Rollback();
     conn1.Close();
     conn2.Close();

     throw ex;
    }
    if(effectrow == 2)
    {
     sqlTran1.Commit();
     sqlTran2.Commit();
    }
    else
    {
     sqlTran1.Rollback();
     sqlTran2.Rollback();
    }

    conn1.Close();
    conn2.Close();
   }
  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.