C#同步SQL Server数据库Schema

本文涉及的产品
云数据库 RDS SQL Server,基础系列 2核4GB
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
简介: 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同步,还可以很多地方可以继续完善,比如约束,双主键,外键等等。

相关实践学习
使用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
目录
打赏
0
0
0
0
20
分享
相关文章
数据库数据恢复—SQL Server报错“错误 823”的数据恢复案例
SQL Server数据库附加数据库过程中比较常见的报错是“错误 823”,附加数据库失败。 如果数据库有备份则只需还原备份即可。但是如果没有备份,备份时间太久,或者其他原因导致备份不可用,那么就需要通过专业手段对数据库进行数据恢复。
【SQL技术】不同数据库引擎 SQL 优化方案剖析
不同数据库系统(MySQL、PostgreSQL、Doris、Hive)的SQL优化策略。存储引擎特点、SQL执行流程及常见操作(如条件查询、排序、聚合函数)的优化方法。针对各数据库,索引使用、分区裁剪、谓词下推等技术,并提供了具体的SQL示例。通用的SQL调优技巧,如避免使用`COUNT(DISTINCT)`、减少小文件问题、慎重使用`SELECT *`等。通过合理选择和应用这些优化策略,可以显著提升数据库查询性能和系统稳定性。
82 9
【潜意识Java】MyBatis中的动态SQL灵活、高效的数据库查询以及深度总结
本文详细介绍了MyBatis中的动态SQL功能,涵盖其背景、应用场景及实现方式。
133 6
使用访问指导(SQL Access Advisor)优化数据库业务负载
本文介绍了Oracle的SQL访问指导(SQL Access Advisor)的应用场景及其使用方法。访问指导通过分析给定的工作负载,提供索引、物化视图和分区等方面的优化建议,帮助DBA提升数据库性能。具体步骤包括创建访问指导任务、创建工作负载、连接工作负载至访问指导、设置任务参数、运行访问指导、查看和应用优化建议。访问指导不仅针对单条SQL语句,还能综合考虑多条SQL语句的优化效果,为DBA提供全面的决策支持。
104 11
SQL Servers审核提高数据库安全性
SQL Server审核是一种追踪和审查SQL Server上所有活动的机制,旨在检测潜在威胁和漏洞,监控服务器设置的更改。审核日志记录安全问题和数据泄露的详细信息,帮助管理员追踪数据库中的特定活动,确保数据安全和合规性。SQL Server审核分为服务器级和数据库级,涵盖登录、配置变更和数据操作等事件。审核工具如EventLog Analyzer提供实时监控和即时告警,帮助快速响应安全事件。
MySQL导入.sql文件后数据库乱码问题
本文分析了导入.sql文件后数据库备注出现乱码的原因,包括字符集不匹配、备注内容编码问题及MySQL版本或配置问题,并提供了详细的解决步骤,如检查和统一字符集设置、修改客户端连接方式、检查MySQL配置等,确保导入过程顺利。
gbase 8a 数据库 SQL合并类优化——不同数据统计周期合并为一条SQL语句
gbase 8a 数据库 SQL合并类优化——不同数据统计周期合并为一条SQL语句
gbase 8a 数据库 SQL优化案例-关联顺序优化
gbase 8a 数据库 SQL优化案例-关联顺序优化
Windows下C# 通过ADO.NET方式连接南大通用GBase 8s数据库(上)
Windows下C# 通过ADO.NET方式连接南大通用GBase 8s数据库(上)
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等