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

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: C#同步SQL Server数据库中的数据 1. 先写个sql处理类: using System;using System.Collections.

C#同步SQL Server数据库中的数据

1. 先写个sql处理类:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace PinkDatabaseSync
{
    class DBUtility : IDisposable
    {
        private string Server;
        private string Database;
        private string Uid;
        private string Password;
        private string connectionStr;
        private SqlConnection mySqlConn;

        public void EnsureConnectionIsOpen()
        {
            if (mySqlConn == null)
            {
                mySqlConn = new SqlConnection(this.connectionStr);
                mySqlConn.Open();
            }
            else if (mySqlConn.State == ConnectionState.Closed)
            {
                mySqlConn.Open();
            }
        }

        public DBUtility(string server, string database, string uid, string password)
        {
            this.Server = server;
            this.Database = database;
            this.Uid = uid;
            this.Password = password;
            this.connectionStr = "Server=" + this.Server + ";Database=" + this.Database + ";User Id=" + this.Uid + ";Password=" + this.Password;
        }

        public int ExecuteNonQueryForMultipleScripts(string sqlStr)
        {
            this.EnsureConnectionIsOpen();
            SqlCommand cmd = mySqlConn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sqlStr;
            return cmd.ExecuteNonQuery();
        }
        public int ExecuteNonQuery(string sqlStr)
        {
            this.EnsureConnectionIsOpen();
            SqlCommand cmd = new SqlCommand(sqlStr, mySqlConn);
            cmd.CommandType = CommandType.Text;
            return cmd.ExecuteNonQuery();
        }


        public object ExecuteScalar(string sqlStr)
        {
            this.EnsureConnectionIsOpen();
            SqlCommand cmd = new SqlCommand(sqlStr, mySqlConn);
            cmd.CommandType = CommandType.Text;
            return cmd.ExecuteScalar();
        }

        public DataSet ExecuteDS(string sqlStr)
        {
            DataSet ds = new DataSet();
            this.EnsureConnectionIsOpen();
            SqlDataAdapter sda= new SqlDataAdapter(sqlStr,mySqlConn);
            sda.Fill(ds);
            return ds;
        }

        public void BulkCopyTo(string server, string database, string uid, string password, string tableName, string primaryKeyName)
        {
            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();

            SqlDataReader readerSource = cmd.ExecuteReader();
            bool isSourceContainsData = false;
            string whereClause = " where ";
            while (readerSource.Read())
            {
                isSourceContainsData = true;
                whereClause += " " + primaryKeyName + "!=" + readerSource[primaryKeyName].ToString() + " and ";
            }
            whereClause = whereClause.Remove(whereClause.Length - " and ".Length, " and ".Length);
            readerSource.Close();

            whereClause = isSourceContainsData ? whereClause : string.Empty;

            // Select data from Products table
            cmd = new SqlCommand("SELECT * FROM " + tableName + whereClause, mySqlConn);
            // Execute reader
            SqlDataReader reader = cmd.ExecuteReader();
            // Create SqlBulkCopy
            SqlBulkCopy bulkData = new SqlBulkCopy(destinationConnector);
            // Set destination table name
            bulkData.DestinationTableName = tableName;
            // Write data
            bulkData.WriteToServer(reader);
            // Close objects
            bulkData.Close();
            destinationConnector.Close();
            mySqlConn.Close();
        }

        public void Dispose()
        {
            if (mySqlConn != null)
                mySqlConn.Close();
        }
    }
}


2. 再写个数据库类型类:

using System;
using System.Collections.Generic;
using System.Text;

namespace PinkDatabaseSync
{
    public class SQLDBSystemType
    {
        public static Dictionary<string, string> systemTypeDict
        {
            get{
            var systemTypeDict = new Dictionary<string, string>();
            systemTypeDict.Add("34", "image");
            systemTypeDict.Add("35", "text");
            systemTypeDict.Add("36", "uniqueidentifier");
            systemTypeDict.Add("40", "date");
            systemTypeDict.Add("41", "time");
            systemTypeDict.Add("42", "datetime2");
            systemTypeDict.Add("43", "datetimeoffset");
            systemTypeDict.Add("48", "tinyint");
            systemTypeDict.Add("52", "smallint");
            systemTypeDict.Add("56", "int");
            systemTypeDict.Add("58", "smalldatetime");
            systemTypeDict.Add("59", "real");
            systemTypeDict.Add("60", "money");
            systemTypeDict.Add("61", "datetime");
            systemTypeDict.Add("62", "float");
            systemTypeDict.Add("98", "sql_variant");
            systemTypeDict.Add("99", "ntext");
            systemTypeDict.Add("104", "bit");
            systemTypeDict.Add("106", "decimal");
            systemTypeDict.Add("108", "numeric");
            systemTypeDict.Add("122", "smallmoney");
            systemTypeDict.Add("127", "bigint");
            systemTypeDict.Add("240-128", "hierarchyid");
            systemTypeDict.Add("240-129", "geometry");
            systemTypeDict.Add("240-130", "geography");
            systemTypeDict.Add("165", "varbinary");
            systemTypeDict.Add("167", "varchar");
            systemTypeDict.Add("173", "binary");
            systemTypeDict.Add("175", "char");
            systemTypeDict.Add("189", "timestamp");
            systemTypeDict.Add("231", "nvarchar");
            systemTypeDict.Add("239", "nchar");
            systemTypeDict.Add("241", "xml");
            systemTypeDict.Add("231-256", "sysname");
            return systemTypeDict;
            }
        }
    }
}


3. 写个同步数据库中的数据:
public void BulkCopyTo(string server, string database, string uid, string password, string tableName, string primaryKeyName)
        {
            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();

            SqlDataReader readerSource = cmd.ExecuteReader();
            bool isSourceContainsData = false;
            string whereClause = " where ";
            while (readerSource.Read())
            {
                isSourceContainsData = true;
                whereClause += " " + primaryKeyName + "!=" + readerSource[primaryKeyName].ToString() + " and ";
            }
            whereClause = whereClause.Remove(whereClause.Length - " and ".Length, " and ".Length);
            readerSource.Close();

            whereClause = isSourceContainsData ? whereClause : string.Empty;

            // Select data from Products table
            cmd = new SqlCommand("SELECT * FROM " + tableName + whereClause, mySqlConn);
            // Execute reader
            SqlDataReader reader = cmd.ExecuteReader();
            // Create SqlBulkCopy
            SqlBulkCopy bulkData = new SqlBulkCopy(destinationConnector);
            // Set destination table name
            bulkData.DestinationTableName = tableName;
            // Write data
            bulkData.WriteToServer(reader);
            // Close objects
            bulkData.Close();
            destinationConnector.Close();
            mySqlConn.Close();
        }


 

4. 最后执行同步函数:

private void SyncDB_Click(object sender, EventArgs e)
        {
            string server = "localhost";
            string dbname = "pinkCRM";
            string uid = "sa";
            string password = "password";
            string server2 = "server2";
            string dbname2 = "pinkCRM2";
            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;
                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();
                    db.BulkCopyTo(server2, dbname2, uid2, password2, tableName, primaryKeyName);
                 
                    LogView.Text = LogView.Text +"Done sync data for table:"+ tableName+ 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
目录
相关文章
|
5天前
|
SQL 存储 Oracle
Oracle的PL/SQL定义变量和常量:数据的稳定与灵动
【4月更文挑战第19天】在Oracle PL/SQL中,变量和常量扮演着数据存储的关键角色。变量是可变的“魔术盒”,用于存储程序运行时的动态数据,通过`DECLARE`定义,可在循环和条件判断中体现其灵活性。常量则是不可变的“固定牌”,一旦设定值便保持不变,用`CONSTANT`声明,提供程序稳定性和易维护性。通过 `%TYPE`、`NOT NULL`等特性,可以更高效地管理和控制变量与常量,提升代码质量。善用两者,能优化PL/SQL程序的结构和性能。
|
2天前
|
SQL Oracle 关系型数据库
sql语句创建数据库
在创建数据库之前,请确保你有足够的权限,并且已经考虑了数据库的安全性和性能需求。此外,不同的DBMS可能有特定的最佳实践和配置要求,因此建议查阅相关DBMS的官方文档以获取更详细和准确的信息。
|
2天前
|
SQL 缓存 数据库
sql 数据库优化
SQL数据库优化是一个复杂且关键的过程,涉及多个层面的技术和策略。以下是一些主要的优化建议: 查询语句优化: 避免全表扫描:在查询时,尽量使用索引来减少全表扫描,提高查询速度。 使用合适的子查询方式:子查询可能降低查询效率,但可以通过优化子查询的结构或使用连接(JOIN)替代子查询来提高性能。 简化查询语句:避免不必要的复杂查询,尽量使SQL语句简单明了。 使用EXISTS替代IN:在查询数据是否存在时,使用EXISTS通常比IN更快。 索引优化: 建立合适的索引:对于经常查询的列,如主键和外键,应创建相应的索引。同时,考虑使用覆盖索引来进一步提高性能。 避免过多的索引:虽然索引可以提高查询
|
2天前
|
SQL XML 数据库
sql导入数据库命令
在SQL Server中,数据库导入可通过多种方式实现:1) 使用SSMS的“导入数据”向导从各种源(如Excel、CSV)导入;2) BULK INSERT语句适用于导入文本文件;3) bcp命令行工具进行批量数据交换;4) OPENROWSET函数直接从外部数据源(如Excel)插入数据。在操作前,请记得备份数据库,并可能需对数据进行预处理以符合SQL Server要求。注意不同方法可能依版本和配置而异。
|
5天前
|
SQL Oracle 关系型数据库
Oracle的PL/SQL游标属性:数据的“导航仪”与“仪表盘”
【4月更文挑战第19天】Oracle PL/SQL游标属性如同车辆的导航仪和仪表盘,提供丰富信息和控制。 `%FOUND`和`%NOTFOUND`指示数据读取状态,`%ROWCOUNT`记录处理行数,`%ISOPEN`显示游标状态。还有`%BULK_ROWCOUNT`和`%BULK_EXCEPTIONS`增强处理灵活性。通过实例展示了如何在数据处理中利用这些属性监控和控制流程,提高效率和准确性。掌握游标属性是提升数据处理能力的关键。
|
5天前
|
SQL Oracle 安全
Oracle的PL/SQL循环语句:数据的“旋转木马”与“无限之旅”
【4月更文挑战第19天】Oracle PL/SQL中的循环语句(LOOP、EXIT WHEN、FOR、WHILE)是处理数据的关键工具,用于批量操作、报表生成和复杂业务逻辑。LOOP提供无限循环,可通过EXIT WHEN设定退出条件;FOR循环适用于固定次数迭代,WHILE循环基于条件判断执行。有效使用循环能提高效率,但需注意避免无限循环和优化大数据处理性能。掌握循环语句,将使数据处理更加高效和便捷。
|
5天前
|
SQL Oracle 关系型数据库
Oracle的PL/SQL条件控制:数据的“红绿灯”与“分岔路”
【4月更文挑战第19天】在Oracle PL/SQL中,IF语句与CASE语句扮演着数据流程控制的关键角色。IF语句如红绿灯,依据条件决定程序执行路径;ELSE和ELSIF提供多分支逻辑。CASE语句则是分岔路,按表达式值选择执行路径。这些条件控制语句在数据验证、错误处理和业务逻辑中不可或缺,通过巧妙运用能实现高效程序逻辑,保障数据正确流转,支持企业业务发展。理解并熟练掌握这些语句的使用是成为合格数据管理员的重要一环。
|
5天前
|
SQL Oracle 关系型数据库
Oracle的PL/SQL表达式:数据的魔法公式
【4月更文挑战第19天】探索Oracle PL/SQL表达式,体验数据的魔法公式。表达式结合常量、变量、运算符和函数,用于数据运算与转换。算术运算符处理数值计算,比较运算符执行数据比较,内置函数如TO_CHAR、ROUND和SUBSTR提供多样化操作。条件表达式如CASE和NULLIF实现灵活逻辑判断。广泛应用于SQL查询和PL/SQL程序,助你驾驭数据,揭示其背后的规律与秘密,成为数据魔法师。
|
5天前
|
关系型数据库 MySQL 分布式数据库
《MySQL 简易速速上手小册》第6章:MySQL 复制和分布式数据库(2024 最新版)
《MySQL 简易速速上手小册》第6章:MySQL 复制和分布式数据库(2024 最新版)
35 2
|
21天前
|
SQL 数据可视化 关系型数据库
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
104 0

热门文章

最新文章