【问题标题】:How can I synchronise two datatables and update the target in the database?如何同步两个数据表并更新数据库中的目标?
【发布时间】:2011-02-09 16:48:42
【问题描述】:

我正在尝试在两个数据库之间同步两个表。我认为最好的方法是使用 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]);
            }

        }

目前,源中有一行不在目标中。该行永远不会被转移。我也试过用空的目标,没有任何转移。

【问题讨论】:

  • 对 targetDs.Tables[0] 的监视显示正确的数据,但未将其发送到数据库。我不确定 InsertCommand 等行,但没有我所拥有的,这些命令是空的。
  • 嗯,你有没有试过在 targetAdapter.Update() 方法之前添加 targetDs.AcceptChanges() ?
  • 是的,那也没用。

标签: c# merge datatable sqldataadapter


【解决方案1】:

这可能有点矫枉过正,但你可以试试Sync Framework from Microsoft

【讨论】:

    【解决方案2】:

    我知道这不是直接回答你的问题,但你看过Microsoft Sync Framework吗?

    它被设计用来做这类事情,并且为你做大部分(如果不是全部)驴子的工作。

    【讨论】:

    • 我现在正在看。从我所看到的来看,它并不是很轻!
    • @Craig - 我并不是说它适用于所有情况,但是要同步 600 个表,它可能比手动执行更好。
    猜你喜欢
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多