2010-04-19 38 views
2

我想同步兩個數據庫之間的兩個表。我認爲最好的方法是使用DataTable.Merge方法。這似乎可以看到變化,但沒有任何事情會被提交到數據庫。如何同步兩個數據表並更新數據庫中的目標?

到目前爲止,我有:

string tableName = "[Table_1]"; 
     string sql = "select * from " + tableName; 

     using (SqlConnection sourceConn = new SqlConnection(ConfigurationManager.ConnectionStrings["source"].ConnectionString)) 
     { 
      SqlDataAdapter sourceAdapter = new SqlDataAdapter(); 

      sourceAdapter.SelectCommand = new SqlCommand(sql, sourceConn); 
      sourceConn.Open(); 
      DataSet sourceDs = new DataSet(); 
      sourceAdapter.Fill(sourceDs); 

      using (SqlConnection targetConn = new SqlConnection(ConfigurationManager.ConnectionStrings["target"].ConnectionString)) 
      { 
       SqlDataAdapter targetAdapter = new SqlDataAdapter(); 

       targetAdapter.SelectCommand = new SqlCommand(sql, targetConn); 

       SqlCommandBuilder builder = new SqlCommandBuilder(targetAdapter); 

       targetAdapter.InsertCommand = builder.GetInsertCommand(); 
       targetAdapter.UpdateCommand = builder.GetUpdateCommand(); 
       targetAdapter.DeleteCommand = builder.GetDeleteCommand(); 

       targetConn.Open(); 
       DataSet targetDs = new DataSet(); 
       targetAdapter.Fill(targetDs); 

       targetDs.Tables[0].TableName = tableName; 
       sourceDs.Tables[0].TableName = tableName; 
       targetDs.Tables[0].Merge(sourceDs.Tables[0]); 

       targetAdapter.Update(targetDs.Tables[0]); 
      } 

     } 

目前,存在這樣是不是在目標的源一行。此行從不轉移。我也嘗試了一個空目標,沒有任何東西被轉移。

+0

手錶[0]顯示正確的數據,但它不會被髮送到數據庫中。 我不確定InsertCommand等,行,但沒有我在那裏,命令爲空。 – Craig 2010-04-19 13:42:44

+0

嗯,你有沒有嘗試在targetAdapter.Update()方法之前添加targetDs.AcceptChanges()? – code4life 2010-04-20 02:30:11

+0

是的,這也沒有工作。 – Craig 2010-04-20 13:32:27

回答

0

我知道這不是直接回答你的問題,而是你看了看Microsoft Sync Framework

它的目的是做這種事情,併爲你做大部分(如果不是全部)驢工作。

+0

我正在看那個。從我所能看到的來看,它並不輕巧! – Craig 2010-04-19 15:15:37

+0

@克雷格 - 我不是故意暗示它適合所有情況,但有600個表來同步它可能比手動更好。 – ChrisF 2010-04-19 19:22:05

相關問題