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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS SQL Server,基础系列 2核4GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 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());
            }
        }

注: 这里只写了对已有数据的不再插入数据,可以再提高为如果有数据更新,可以进行更新,那么一个数据库同步工具就可以完成了!

目录
相关文章
|
4月前
|
SQL 存储 关系型数据库
第二篇:关系型数据库的核心概念与 SQL 基础
本篇内容深入浅出地讲解了关系型数据库的核心概念与SQL基础,适合有一定计算机基础的学习者。文章涵盖数据库的基本操作(CRUD)、数据类型、表的创建与管理等内容,并通过实例解析SELECT、INSERT、UPDATE、DELETE等语句的用法。此外,还推荐了多种学习资源与实践建议,帮助读者巩固知识。学完后,你将掌握基础数据库操作,为后续高级学习铺平道路。
219 1
|
5月前
|
人工智能 运维 关系型数据库
|
5月前
|
SQL 数据库 数据安全/隐私保护
数据库数据恢复——sql server数据库被加密的数据恢复案例
SQL server数据库数据故障: SQL server数据库被加密,无法使用。 数据库MDF、LDF、log日志文件名字被篡改。 数据库备份被加密,文件名字被篡改。
|
3月前
|
SQL 关系型数据库 MySQL
Go语言数据库编程:使用 `database/sql` 与 MySQL/PostgreSQL
Go语言通过`database/sql`标准库提供统一数据库操作接口,支持MySQL、PostgreSQL等多种数据库。本文介绍了驱动安装、连接数据库、基本增删改查操作、预处理语句、事务处理及错误管理等内容,涵盖实际开发中常用的技巧与注意事项,适合快速掌握Go语言数据库编程基础。
257 62
|
2月前
|
SQL XML Java
配置Spring框架以连接SQL Server数据库
最后,需要集成Spring配置到应用中,这通常在 `main`方法或者Spring Boot的应用配置类中通过加载XML配置或使用注解来实现。
241 0
|
4月前
|
SQL 关系型数据库 MySQL
SQL在线美化工具
SQL 在线美化工具是一款智能代码格式化工具,专为开发者、数据分析师及数据库管理员设计。支持自动缩进、语法高亮、关键字优化(大写/小写)及语法错误提示,兼容MySQL、PostgreSQL等多种SQL方言,可快速将杂乱SQL语句转换为专业易读的格式,提升代码维护效率和团队协作体验。
345 19
|
3月前
|
SQL 人工智能 关系型数据库
GitHub 热门!MindsDB 破解 AI + 数据库瓶颈,究竟有什么惊艳亮点?只需 SQL 即可实现智能预测
MindsDB 是一款将 AI 能力直接注入数据库的开源工具,支持 MySQL、PostgreSQL 等多种数据库连接,通过 SQL 即可完成模型训练与预测。它提供 AutoML 引擎、LLM 集成、联邦查询等功能,简化 MLOps 流程,实现数据到智能的无缝衔接。项目在 GitHub 上已获 32.4k 星,社区活跃,适用于客户流失预警、推荐系统、情感分析等场景。开发者无需深入模型细节,即可快速构建智能解决方案。项目地址:https://github.com/mindsdb/mindsdb。
715 0
|
5月前
|
SQL 关系型数据库 MySQL
大数据新视界--大数据大厂之MySQL数据库课程设计:MySQL 数据库 SQL 语句调优方法详解(2-1)
本文深入介绍 MySQL 数据库 SQL 语句调优方法。涵盖分析查询执行计划,如使用 EXPLAIN 命令及理解关键指标;优化查询语句结构,包括避免子查询、减少函数使用、合理用索引列及避免 “OR”。还介绍了索引类型知识,如 B 树索引、哈希索引等。结合与 MySQL 数据库课程设计相关文章,强调 SQL 语句调优重要性。为提升数据库性能提供实用方法,适合数据库管理员和开发人员。
|
5月前
|
关系型数据库 MySQL 大数据
大数据新视界--大数据大厂之MySQL 数据库课程设计:MySQL 数据库 SQL 语句调优的进阶策略与实际案例(2-2)
本文延续前篇,深入探讨 MySQL 数据库 SQL 语句调优进阶策略。包括优化索引使用,介绍多种索引类型及避免索引失效等;调整数据库参数,如缓冲池、连接数和日志参数;还有分区表、垂直拆分等其他优化方法。通过实际案例分析展示调优效果。回顾与数据库课程设计相关文章,强调全面认识 MySQL 数据库重要性。为读者提供综合调优指导,确保数据库高效运行。
|
8月前
|
关系型数据库 MySQL 数据库连接
数据库连接工具连接mysql提示:“Host ‘172.23.0.1‘ is not allowed to connect to this MySQL server“
docker-compose部署mysql8服务后,连接时提示不允许连接问题解决