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. 文件不 ...
随机推荐
- github-vimium-compile-crx
chrome-62.x版本上安装vimium 1.61.1 https://blog.csdn.net/ZHUJIANWEILI4/article/details/78385346
- 驱动程序调试方法之printk——自制proc文件(二)
上一节的程序很振奋人心,我们自己实现了一个myprintk打印函数.但是这个函数存在一个致命的缺陷,那就是只能使用一次cat /proc/mymsg命令来读取mylog_buf的值.这是因为读到最后会 ...
- [Angular Directive] Combine HostBinding with Services in Angular 2 Directives
You can change behaviors of element and @Component properties based on services using @HostBinding i ...
- 【poj2528】Mayor's posters
Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 59254 Accepted: 17167 Description The ...
- ASP.net 中 OutputCache 指令各个参数的作用。
使用@ OutputCache指令 使用@ OutputCache指令,能够实现对页面输出缓存的一般性需要.@ OutputCache指令在ASP.NET页或者页中包含的用户控件的头部声明.这种方式非 ...
- js时间和时间戳之间如何转换(汇总)
js时间和时间戳之间如何转换(汇总) 一.总结 一句话总结: 1.js中通过new Date()来获取时间对象, 2.这个时间对象可以通过getTime()方法获取时间戳, 3.也可以通过getYea ...
- 机器学习:Softmax Classifier (两个隐含层)
程序实现 softmax classifier, 含有两个隐含层的情况.activation function 是 ReLU : f(x)=max(0,x) f1=w1x+b1 h1=max(0,f1 ...
- Erlang 聊天室程序
Erlang 聊天室程序( 一) Erlang 聊天室程序(二) 客户端的退出 Erlang 聊天室程序(三) 数据交换格式---json的decode Erlang 聊天室程序(四) 数据交换格式- ...
- Hibernate中的配置文件
Hibernate中配置文件 主配置文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE h ...
- 【17.69%】【codeforces 659F】Polycarp and Hay
time limit per test4 seconds memory limit per test512 megabytes inputstandard input outputstandard o ...