C#同步SQL Server数据库Schema
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的更多相关文章
- C#同步SQL Server数据库中的数据--数据库同步工具[同步新数据]
C#同步SQL Server数据库中的数据 1. 先写个sql处理类: using System; using System.Collections.Generic; using System.Dat ...
- SQL SERVER 数据库表同步复制 笔记
SQL SERVER 数据库表同步复制 笔记 同步复制可运行在不同版本的SQL Server服务之间 环境模拟需要两台数据库192.168.1.1(发布),192.168.1.10(订阅) 1.在发布 ...
- SQL Server 数据库同步,订阅、发布、复制、跨服务器
随便说两句 折腾了一周,也算把数据库同步弄好了.首先局域网内搭建好,进行各种测试,弄的时候各种问题,弄好以后感觉还是挺简单的.本地测试好了,又在服务器进行测试,主要的难点就是跨网段同步,最后也解决了, ...
- Microsoft SQL Server 数据库 错误号大全
panchzh :Microsoft SQL Server 数据库 错误号大全0 操作成功完成. 1 功能错误. 2 系统找不到指定的文件. 3 系统找不到指定的路径. 4 系统无法打开文件. 5 拒 ...
- SQL Server 数据库部分常用语句小结(三)
21.SQL运行Log的读取 .EXEC xp_readerrorlog 0,1,null,null,'开始时间','结束时间' 22. Alwayson 状况及传输情况监控 SELECT ar.re ...
- SQL Server数据库镜像的页面自动修复原理
SQL Server数据库镜像的页面自动修复原理 主库页面损坏 镜像库页面损坏 LSN用来保证事务的时序 LSN保存在每个数据页面的页头 在同一台机器,内存中的数据页和磁盘中的数据页保持同步依靠的是数 ...
- Sql Server数据库备份和恢复:原理篇
本文与您探讨为什么Sql Server有完整备份.差异备份和事务日志备份三种备份方式,以及为什么数据库又有简单模式.完整模式和大容量日志模式这三种恢复模式.本文内容适用于2005以上所有版本的Sql ...
- SQL Server数据库与max degree of parallelism参数
我们今天主要向大家讲述的是SQL Server数据库中的max degree of parallelism参数,当 SQL Server 数据库在具N个微处理器或是 CPU 的计算机上运行时,它将为每 ...
- SQL Server 数据库文件管理
关于数据库文件的管理问题,我经常说,常在江湖混,哪有不挨棍,用的时间长了,基本上都有遇到一些数据库文件管理上的问题,比如说: 1. SQL Server数据文件空间满 2. 日志文件暴涨 3. 文件不 ...
随机推荐
- [CSS] Conditionally Apply Styles Using Feature Queries @supports
While browsers do a great job of ignoring styles they don’t understand, it can be useful to provide ...
- js进阶 11-18 jquery中操作选择器的方法有哪些
js进阶 11-18 jquery中操作选择器的方法有哪些 一.总结 一句话总结:add().addBack().end() 1.add()方法是干嘛的,举一例? 将add()方法后选择器选择的jqu ...
- js课程 1-2 js概念
js课程 1-2 js概念 一.总结 一句话总结:js标签元素也是js对象,有属性和方法,方法就是事件,属性就是标签属性,可以直接调用. 1.js中如何获取标签对象? getElement获取的是标 ...
- Tampermonkey版Vimium
Tampermonkey版Vimium https://zhuanlan.zhihu.com/p/27222664
- gitlab+jenkins+pm2+rsync实现node的自动化部署
环境配置 jenkins java环境 yum install -y java 安装jenkins wget -O /etc/yum.repos.d/jenkins.repo http://pkg.j ...
- 【poj 1704】Georgia and Bob
Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 9776 Accepted: 3222 Description Georgia a ...
- 【codeforces 602D】Lipshitz Sequence
time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...
- 【hdu 2486】A simple stone game
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s) ...
- Java相关思维导图分享
非常多朋友都给我发私信希望获得一份Java知识的思维导图,我来不及一一答复.原先是给大家一个百度网盘的链接分享,大家能够自己去下载,可是不知道云盘还能用多久.把相关资源转移到了QQ的群共享中.须要的朋 ...
- 毕设三: spark与phoenix集成插入数据/解析json数组
需求:将前些日子采集的评论存储到hbase中 思路: 先用fastjson解析评论,然后构造rdd,最后使用spark与phoenix交互,把数据存储到hbase中 部分数据: [ { "r ...