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同步。还能够非常多地方要继续完好,例如,约束。双主密钥。外键等。。

版权声明:本文博客原创文章。博客,未经同意,不得转载。

C#同步SQL Server数据库Schema的更多相关文章

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

    C#同步SQL Server数据库中的数据 1. 先写个sql处理类: using System; using System.Collections.Generic; using System.Dat ...

  2. SQL SERVER 数据库表同步复制 笔记

    SQL SERVER 数据库表同步复制 笔记 同步复制可运行在不同版本的SQL Server服务之间 环境模拟需要两台数据库192.168.1.1(发布),192.168.1.10(订阅) 1.在发布 ...

  3. SQL Server 数据库同步,订阅、发布、复制、跨服务器

    随便说两句 折腾了一周,也算把数据库同步弄好了.首先局域网内搭建好,进行各种测试,弄的时候各种问题,弄好以后感觉还是挺简单的.本地测试好了,又在服务器进行测试,主要的难点就是跨网段同步,最后也解决了, ...

  4. Microsoft SQL Server 数据库 错误号大全

    panchzh :Microsoft SQL Server 数据库 错误号大全0 操作成功完成. 1 功能错误. 2 系统找不到指定的文件. 3 系统找不到指定的路径. 4 系统无法打开文件. 5 拒 ...

  5. SQL Server 数据库部分常用语句小结(三)

    21.SQL运行Log的读取 .EXEC xp_readerrorlog 0,1,null,null,'开始时间','结束时间' 22. Alwayson 状况及传输情况监控 SELECT ar.re ...

  6. SQL Server数据库镜像的页面自动修复原理

    SQL Server数据库镜像的页面自动修复原理 主库页面损坏 镜像库页面损坏 LSN用来保证事务的时序 LSN保存在每个数据页面的页头 在同一台机器,内存中的数据页和磁盘中的数据页保持同步依靠的是数 ...

  7. Sql Server数据库备份和恢复:原理篇

    本文与您探讨为什么Sql Server有完整备份.差异备份和事务日志备份三种备份方式,以及为什么数据库又有简单模式.完整模式和大容量日志模式这三种恢复模式.本文内容适用于2005以上所有版本的Sql ...

  8. SQL Server数据库与max degree of parallelism参数

    我们今天主要向大家讲述的是SQL Server数据库中的max degree of parallelism参数,当 SQL Server 数据库在具N个微处理器或是 CPU 的计算机上运行时,它将为每 ...

  9. SQL Server 数据库文件管理

    关于数据库文件的管理问题,我经常说,常在江湖混,哪有不挨棍,用的时间长了,基本上都有遇到一些数据库文件管理上的问题,比如说: 1. SQL Server数据文件空间满 2. 日志文件暴涨 3. 文件不 ...

随机推荐

  1. 解决maven项目找不到maven依赖的解决办法

    不同的IDE对应的.classpath中的maven声明也不一样,这样就会导致项目找不到maven依赖. 即Java Build Path--->Libraries中找不到Maven Depen ...

  2. ios开发多线程四:NSOperation多图下载综合案例

    #import "ViewController.h" #import "XMGAPP.h" @interface ViewController () /** t ...

  3. Json入门 分类: C_OHTERS 2014-04-23 16:20 601人阅读 评论(0) 收藏

    参考<疯狂android讲义>>730页 JSON的基础请参考W3SCHOOL的教程: http://www.w3school.com.cn/json/index.asp 例子: h ...

  4. iOS writeTofile 和对象的序列化

    前言:做了一个图片浏览的小demo,支持随意添加.删除图片,图片放大.缩小,带矩形框的截图.随后几篇博客都会详细讲解在此过程中遇到的各种问题.这篇主要讲,在做添加.删除这个功能时,遇到的存文件的问题. ...

  5. js课程 1-2 js概念

    js课程 1-2  js概念 一.总结 一句话总结:js标签元素也是js对象,有属性和方法,方法就是事件,属性就是标签属性,可以直接调用. 1.js中如何获取标签对象? getElement获取的是标 ...

  6. Android 比较两个时间段是否有交集或重复

    先看一个例图: 在金山<电池管家>应用中就有一个类似上图这样的功能—— 开启多个定时任务. 当开启另一个定时任务的时候,如果即将开启的这个定时任务的时间段与已经开启了的定时任务的时间段有交 ...

  7. &quot;Swift&quot;编程语言

    来自英文文档.百度翻译以及自己没过4级的渣渣英语功底,为了自己以后看起来方便 About Swift 关于"海燕" IMPORTANT 重要 This is a prelimina ...

  8. 将asp.net core2.0项目部署在IIS上运行

    原文:将asp.net core2.0项目部署在IIS上运行 前言:  与ASP.NET时代不同,ASP.NET Core不再是由IIS工作进程(w3wp.exe)托管,而是独立运行的.它独立运行在控 ...

  9. [Django] Get started with Django -- Install python and virtualenv

    Install python3 on MacOS: brew install python3 Come alone with python3, there are also some other to ...

  10. 进入Erlang的世界

    http://erlang.group.iteye.com/group/wiki/1407-to-enter-the-world-of-erlang 进入Erlang的世界 作为程序员,我们曾经闻听很 ...