c# - 如何同步两个数据表并更新数据库中的目标?

标签 c# merge datatable sqldataadapter

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

        }

目前,源中有一行不在目标中。此行永远不会传输。我也用空目标尝试过,没有任何转移。

最佳答案

我知道它没有直接回答你的问题,但你看过 Microsoft Sync Framework 了吗? ?

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

关于c# - 如何同步两个数据表并更新数据库中的目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2667787/

相关文章:

c# - 在 lambda 中使用变量

c# - 从数据表中的数据列中选择唯一值?

javascript - 数据表大小变化

jsf - 更改 p :graphicImage in p:dataExporter 的导出值

c# - 创建构造函数时报错 "member names cannot be the same as their enclosing type"是什么意思,如何解决?

c# - 从 C# 调用 C++ DLL 的类成员

c# - 网格内的 ContentControl 无法正确调整大小

php - 需要将工作 php 代码转换为函数(随机合并 mp3 文件)

svn - 提交前显示合并历史

algorithm - 理解归并排序的递归