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. 文件不 ...
随机推荐
- WEB应用图片的格式,以及各自的特点和优化(一) by FungLeo
WEB应用图片的格式,以及各自的特点和优化(一) by FungLeo 前言 12年前我入行三天.用table布局做了一个非常粗糙的网页.我说了一句话,"网页就是表格加文字加图片,图片分两种 ...
- php javascript的ajax
先说基础一点的get类型的ajax function loadXMLDoc() { var xmlhttp;//首先判断浏览器是否支持xmlhttprequest,因为ie56不是这个对象,是acti ...
- 程序猿的还有一出路:大数据project师
非常多年前我非常郁闷地写了一篇博客<程序猿的出路在哪里?>,之所以郁闷.我记得是看了中国男足的比赛,不由自主对照自已苦逼的程序猿生涯,以前对中国软件的感情有如对中国男足,绝望到没有不论什么 ...
- winfrom RichTextBox每行字体的颜色
public static void AppendTextColorful(this RichTextBox rtBox, string text, Color color, bool addNewL ...
- 【u028】数列的整除性
Time Limit: 1 second Memory Limit: 128 MB [问题描述] 对于任意一个整数数列,我们可以在每两个整数中间任意放一个符号'+'或'-',这样就可以构成一个表达式, ...
- [NPM] Pass arguments to npm scripts
Often times you’ll have variations that you’ll want to make to your npm scripts and repeating yourse ...
- Warning: file_put_contents(常用单词1.txt): failed to open stream: Invalid argument in
Warning: file_put_contents(常用单词1.txt): failed to open stream: Invalid argument in 一.总结 1.上述问题是因为Win ...
- js如何遍历表单所有控件
js如何遍历表单所有控件 一.总结 一句话总结: 1.获取form表单里面的的所有元素:通过formelement.elements,这里form元素通过name属性直接定位 var fele=for ...
- numpy tricks(二)—— 删除多维数组的行或列
numpy.delete numpy 下的多维数组,如果要删除其中的某些行,或某些列,不可以用置空的方式,进行设置: A[1, :] = None, ⇒ 会将 A 中的第一行数据全部置为 Nan 1. ...
- iOS 一个简单的单例
比如我有一个Singleton的类(DemoStatusManage),他有一个实例方法currentStatus会返回一个1-100的随机数. @interface DemoStatusManage ...