C#同步SQL Server数据库Schema

简介: C#同步SQL Server数据库Schema 1. 先写个sql处理类: using System;using System.Collections.

C#同步SQL Server数据库Schema

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 sqlConn;

        public void EnsureConnectionIsOpen()
        {
            if (sqlConn == null)
            {
                sqlConn = new SqlConnection(this.connectionStr);
                sqlConn.Open();
            }
            else if (sqlConn.State == ConnectionState.Closed)
            {
                sqlConn.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)
        {
            EnsureConnectionIsOpen();
            SqlCommand cmd = sqlConn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sqlStr;
            return cmd.ExecuteNonQuery();
        }
        public int ExecuteNonQuery(string sqlStr)
        {
            EnsureConnectionIsOpen();
            SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);
            cmd.CommandType = CommandType.Text;
            return cmd.ExecuteNonQuery();
        }


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

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

        public void Dispose()
        {
            if (sqlConn != null)
                sqlConn.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. 写个同步数据库表结构schema:

public void SyncDBSchema(string server, string dbname, string uid, string password,
            string server2, string dbname2, string uid2, string password2)
        {
            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;
            string test = string.Empty;
            string newLine = " ";
            foreach (DataRow dr in drc)
            {
                string tableName = dr[0].ToString();
                test += "if NOT exists (select * from sys.objects where name = '" + tableName + "' and type = 'u')";
                test += "CREATE TABLE [dbo].[" + tableName + "](" + newLine;
                DataSet ds2 = db.ExecuteDS("SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('dbo." + tableName + "')");
                DataRowCollection drc2 = ds2.Tables[0].Rows;
                foreach (DataRow dr2 in drc2)
                {
                    test += "[" + dr2["name"].ToString() + "] ";
                    string typeName = SQLDBSystemType.systemTypeDict[dr2["system_type_id"].ToString()];
                    test += "[" + typeName + "]";
                    string charLength = string.Empty;
                    if (typeName.Contains("char"))
                    {
                        charLength = (Convert.ToInt32(dr2["max_length"].ToString()) / 2).ToString();
                        test += "(" + charLength + ")" + newLine;
                    }
                    bool isIdentity = bool.Parse(dr2["is_identity"].ToString());
                    test += isIdentity ? " IDENTITY(1,1)" : string.Empty;
                    bool isNullAble = bool.Parse(dr2["is_nullable"].ToString());
                    test += (isNullAble ? " NULL," : " NOT NULL,") + newLine;
                }
                test += "CONSTRAINT [PK_" + tableName + "] PRIMARY KEY CLUSTERED ";
                string primaryKeyName = drc2[0]["name"].ToString();
                test += @"(
                    	[" + primaryKeyName + @"] ASC
                        )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
                        ) ON [PRIMARY]" + newLine;
            }

            test = "use [" + dbname2 + "]" + newLine + test;
            DBUtility db2 = new DBUtility(server2, dbname2, uid2, password2);
            db2.ExecuteNonQueryForMultipleScripts(test);
        }


4. 最后执行同步函数:

private void SyncDB_Click(object sender, EventArgs e)
        {
            string server = "localhost";
            string dbname = "testdb1";
            string uid = "sa";
            string password = "password1";
            string server2 = "servername2";
            string dbname2 = "testdb2";
            string uid2 = "sa";
            string password2 = "password2";
            try
            {
                SyncDBSchema(server, dbname, uid, password, server2, dbname2, uid2, password2);
                MessageBox.Show("Done sync db schema successfully!");
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }

注: 这只是做个简单的DB schema同步,还可以很多地方可以继续完善,比如约束,双主键,外键等等。

目录
相关文章
|
4月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS费用价格:MySQL、SQL Server、PostgreSQL和MariaDB引擎收费标准
阿里云RDS数据库支持MySQL、SQL Server、PostgreSQL、MariaDB,多种引擎优惠上线!MySQL倚天版88元/年,SQL Server 2核4G仅299元/年,PostgreSQL 227元/年起。高可用、可弹性伸缩,安全稳定。详情见官网活动页。
918 152
|
4月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS支持MySQL、SQL Server、PostgreSQL和MariaDB引擎
阿里云数据库RDS支持MySQL、SQL Server、PostgreSQL和MariaDB引擎,提供高性价比、稳定安全的云数据库服务,适用于多种行业与业务场景。
634 156
|
4月前
|
SQL 人工智能 Linux
SQL Server 2025 RC1 发布 - 从本地到云端的 AI 就绪企业数据库
SQL Server 2025 RC1 发布 - 从本地到云端的 AI 就绪企业数据库
484 5
SQL Server 2025 RC1 发布 - 从本地到云端的 AI 就绪企业数据库
|
8月前
|
SQL 存储 关系型数据库
第二篇:关系型数据库的核心概念与 SQL 基础
本篇内容深入浅出地讲解了关系型数据库的核心概念与SQL基础,适合有一定计算机基础的学习者。文章涵盖数据库的基本操作(CRUD)、数据类型、表的创建与管理等内容,并通过实例解析SELECT、INSERT、UPDATE、DELETE等语句的用法。此外,还推荐了多种学习资源与实践建议,帮助读者巩固知识。学完后,你将掌握基础数据库操作,为后续高级学习铺平道路。
538 1
|
3月前
|
SQL 存储 监控
SQL日志优化策略:提升数据库日志记录效率
通过以上方法结合起来运行调整方案, 可以显著地提升SQL环境下面向各种搜索引擎服务平台所需要满足标准条件下之数据库登记作业流程综合表现; 同时还能确保系统稳健运行并满越用户体验预期目标.
246 6
|
4月前
|
关系型数据库 分布式数据库 数据库
阿里云数据库收费价格:MySQL、PostgreSQL、SQL Server和MariaDB引擎费用整理
阿里云数据库提供多种类型,包括关系型与NoSQL,主流如PolarDB、RDS MySQL/PostgreSQL、Redis等。价格低至21元/月起,支持按需付费与优惠套餐,适用于各类应用场景。
|
4月前
|
SQL Oracle 关系型数据库
Oracle数据库创建表空间和索引的SQL语法示例
以上SQL语法提供了一种标准方式去组织Oracle数据库内部结构,并且通过合理使用可以显著改善查询速度及整体性能。需要注意,在实际应用过程当中应该根据具体业务需求、系统资源状况以及预期目标去合理规划并调整参数设置以达到最佳效果。
374 8
|
5月前
|
SQL 人工智能 Java
用 LangChain4j+Ollama 打造 Text-to-SQL AI Agent,数据库想问就问
本文介绍了如何利用AI技术简化SQL查询操作,让不懂技术的用户也能轻松从数据库中获取信息。通过本地部署PostgreSQL数据库和Ollama模型,结合Java代码,实现将自然语言问题自动转换为SQL查询,并将结果以易懂的方式呈现。整个流程简单直观,适合初学者动手实践,同时也展示了AI在数据查询中的潜力与局限。
671 8
|
7月前
|
SQL 关系型数据库 MySQL
Go语言数据库编程:使用 `database/sql` 与 MySQL/PostgreSQL
Go语言通过`database/sql`标准库提供统一数据库操作接口,支持MySQL、PostgreSQL等多种数据库。本文介绍了驱动安装、连接数据库、基本增删改查操作、预处理语句、事务处理及错误管理等内容,涵盖实际开发中常用的技巧与注意事项,适合快速掌握Go语言数据库编程基础。
577 62
|
5月前
|
SQL 人工智能 Linux
SQL Server 2025 RC0 发布 - 从本地到云端的 AI 就绪企业数据库
SQL Server 2025 RC0 发布 - 从本地到云端的 AI 就绪企业数据库
326 5