C#同步SQL Server数据库中的数据--数据库同步工具[同步已有的有变化的数据]

本文涉及的产品
云数据库 RDS SQL Server,基础系列 2核4GB
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
简介: C#同步SQL Server数据库中的数据--数据库同步工具[同步已有的有变化的数据] 1. C#同步SQL Server数据库Schema 2.

C#同步SQL Server数据库中的数据--数据库同步工具[同步已有的有变化的数据]

1. C#同步SQL Server数据库Schema

2. C#同步SQL Server数据库中的数据--数据库同步工具[同步新数据]

3.  分析下自己写的SQL Server同步工具的性能和缺陷

接着写数据同步,这次可以把有变化的数据进行更新了:

1.SQL批量更新函数:

/// <summary>
        /// Note: for columns, the first string must be primary key name!
        /// </summary>
        /// <param name="server"></param>
        /// <param name="database"></param>
        /// <param name="uid"></param>
        /// <param name="password"></param>
        /// <param name="tableName"></param>
        /// <param name="columns"></param>
        /// <param name="ignoreUpdateColumns"></param>
        public void BulkUpdateTo(string server, string database, string uid, string password, string tableName, List<string> columns, List<string> ignoreUpdateColumns)
        {
            string primaryKeyName = columns[0];
            string connectionString = "Server=" + server + ";Database=" + database + ";User Id=" + uid + ";Password=" + password;
            // Create destination connection
            SqlConnection destinationConnector = new SqlConnection(connectionString);

            SqlCommand cmd = new SqlCommand("SELECT * FROM " + tableName, destinationConnector);
            // Open source and destination connections.
            this.EnsureConnectionIsOpen();
            destinationConnector.Open();

            Dictionary<int, string> Index_PrimaryKeyValue = new Dictionary<int, string>();

            SqlDataReader readerSource = cmd.ExecuteReader();
            Dictionary<string, Dictionary<string, string>> recordsDest = new Dictionary<string, Dictionary<string, string>>();
            int i = 0;
            while (readerSource.Read())
            {
                Index_PrimaryKeyValue.Add(i, readerSource[primaryKeyName].ToString());
                string recordIndex = Index_PrimaryKeyValue[i];
                recordsDest[recordIndex] = new Dictionary<string, string>();
                foreach (string keyName in columns)
                {
                    recordsDest[recordIndex].Add(keyName, readerSource[keyName].ToString());
                }
                i++;
            }

            // Select data from Products table
            cmd = new SqlCommand("SELECT * FROM " + tableName, mySqlConn);
            // Execute reader
            SqlDataReader reader = cmd.ExecuteReader();
            Dictionary<string, Dictionary<string, string>> recordsSource = new Dictionary<string, Dictionary<string, string>>();

            Dictionary<int, string> Index_PrimaryKeyValue2 = new Dictionary<int, string>();

            int j = 0;
            while (reader.Read())
            {
                Index_PrimaryKeyValue2.Add(j, reader[primaryKeyName].ToString());
                string recordIndex = Index_PrimaryKeyValue2[j];
                recordsSource[recordIndex] = new Dictionary<string, string>();
                foreach (string keyName in columns)
                {
                    recordsSource[recordIndex].Add(keyName, reader[keyName].ToString());
                }
                j++;
            }
            reader.Close();
            readerSource.Close();

            foreach (var record in recordsSource)
            {
                string setScripts = string.Empty;
                int setScriptsIndex = 0;
                string primaryKeyValue = record.Key;
                foreach (string keyName in columns)
                {
                    if (!ignoreUpdateColumns.Contains(keyName))
                    {
                        if (recordsDest[primaryKeyValue][keyName] == record.Value[keyName])
                        {
                            //do nothing
                        }
                        else
                        {
                            if (setScriptsIndex == 0)
                            {
                                setScripts += keyName + "='" + recordsSource[primaryKeyValue][keyName] + "' ";
                            }
                            else
                            {
                                setScripts += "," + keyName + "='" + recordsSource[primaryKeyValue][keyName] + "' ";
                            }
                            setScriptsIndex++;
                        }
                    }
                }
                //update source to dest
                if (setScriptsIndex > 0)
                {
                    cmd = new SqlCommand("Update " + tableName + " set " + setScripts + " where " + primaryKeyName + "='" + recordsSource[primaryKeyValue][primaryKeyName] + "'", destinationConnector);
                    cmd.ExecuteNonQuery();
                }
            }

            // Close objects
            destinationConnector.Close();
            mySqlConn.Close();
        }


 

2.调用批量更新函数:

public void syncClick3()
        {
            string server = "server-01";
            string dbname = "dbname1";
            string uid = "sa";
            string password = "password";
            string server2 = "server-02";
            string dbname2 = "dbname2";
            string uid2 = "sa";
            string password2 = "password2";
            try
            {
                LogView.Text = "DB data is syncing!";
                DBUtility db = new DBUtility(server, dbname, uid, password);
                DataSet ds = db.ExecuteDS("SELECT sobjects.name FROM sysobjects sobjects WHERE sobjects.xtype = 'U'");
                DataRowCollection drc = ds.Tables[0].Rows;
                DateTime start = DateTime.Now;
                foreach (DataRow dr in drc)
                {
                    string tableName = dr[0].ToString();
                    LogView.Text = LogView.Text + Environment.NewLine + " syncing table:" + tableName + Environment.NewLine;
                    DataSet ds2 = db.ExecuteDS("SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('dbo." + tableName + "')");
                    DataRowCollection drc2 = ds2.Tables[0].Rows;
                    string primaryKeyName = drc2[0]["name"].ToString();
                    
                    List<string> columns = new List<string>();
                    if (tableName == "Customers")
                    {
                        columns.Add("CustomerName");
                        columns.Add("CustomerId");
                        columns.Add("IsNewData");
                    }
                    else
                    {
                        foreach (DataRow dr2 in drc2)
                        {
                            columns.Add(dr2["name"].ToString());
                        }
                    }
                    List<string> ignoreUpdateColumns = new List<string>();
                    ignoreUpdateColumns.Add("CustomerId");
                    db.BulkUpdateTo(server2, dbname2, uid2, password2, tableName, columns, ignoreUpdateColumns);

                    LogView.Text = LogView.Text + "Done sync data for table:" + tableName + Environment.NewLine;
                }
                DateTime end = DateTime.Now;
                LogView.Text = LogView.Text + "cost total seconds:" + (end - start).TotalSeconds.ToString() + Environment.NewLine;
                MessageBox.Show("Done sync db data successfully!");
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }


至此,一个数据库同步工具的核心代码基本完成!

相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS&nbsp;SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
1月前
|
存储 缓存 数据库
数据库数据删除策略:硬删除vs软删除的最佳实践指南
在项目开发中,“删除”操作常见但方式多样,主要分为硬删除与软删除。硬删除直接从数据库移除数据,操作简单、高效,但不可恢复;适用于临时或敏感数据。软删除通过标记字段保留数据,支持恢复和审计,但增加查询复杂度与数据量;适合需追踪历史或可恢复的场景。两者各有优劣,实际开发中常结合使用以满足不同需求。
91 4
|
2月前
|
数据库 Python
【YashanDB知识库】python驱动查询gbk字符集崖山数据库CLOB字段,数据被驱动截断
【YashanDB知识库】python驱动查询gbk字符集崖山数据库CLOB字段,数据被驱动截断
|
1月前
|
人工智能 关系型数据库 分布式数据库
让数据与AI贴得更近,阿里云瑶池数据库系列产品焕新升级
4月9日阿里云AI势能大会上,阿里云瑶池数据库发布重磅新品及一系列产品能力升级。「推理加速服务」Tair KVCache全新上线,实现KVCache动态分层存储,显著提高内存资源利用率,为大模型推理降本提速。
|
SQL .NET C#
SQL点滴15—在SQL Server 2008中调用C#程序
原文:SQL点滴15—在SQL Server 2008中调用C#程序    T-SQL的在执行普通的查询的时候是很高效的,但是在执行循环,判断这样的语句的时候效率就不那么的高了。这时可以借助CLR了,我们可以在SQL Server 2008中扩展C#程序来完成循环等过程式的查询,或者其他SQL不便实现的功能。
933 0
|
SQL .NET C#
SQL点滴15—在SQL Server 2008中调用C#程序
   T-SQL的在执行普通的查询的时候是很高效的,但是在执行循环,判断这样的语句的时候效率就不那么的高了。这时可以借助CLR了,我们可以在SQL Server 2008中扩展C#程序来完成循环等过程式的查询,或者其他SQL不便实现的功能。
990 0
|
8月前
|
关系型数据库 MySQL 网络安全
5-10Can't connect to MySQL server on 'sh-cynosl-grp-fcs50xoa.sql.tencentcdb.com' (110)")
5-10Can't connect to MySQL server on 'sh-cynosl-grp-fcs50xoa.sql.tencentcdb.com' (110)")
|
10月前
|
SQL 存储 监控
SQL Server的并行实施如何优化?
【7月更文挑战第23天】SQL Server的并行实施如何优化?
278 13
|
10月前
|
SQL
解锁 SQL Server 2022的时间序列数据功能
【7月更文挑战第14天】要解锁SQL Server 2022的时间序列数据功能,可使用`generate_series`函数生成整数序列,例如:`SELECT value FROM generate_series(1, 10)。此外,`date_bucket`函数能按指定间隔(如周)对日期时间值分组,这些工具结合窗口函数和其他时间日期函数,能高效处理和分析时间序列数据。更多信息请参考官方文档和技术资料。
171 9
|
10月前
|
SQL 存储 网络安全
关系数据库SQLserver 安装 SQL Server
【7月更文挑战第26天】
121 6

热门文章

最新文章