usingSystem;
usingSystem.Collections.Generic;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Text;
namespacePinkDatabaseSync
{
classDBUtility:IDisposable
{
privatestringServer;
privatestringDatabase;
privatestringUid;
privatestringPassword;
privatestringconnectionStr;
privateSqlConnectionsqlConn;
publicvoidEnsureConnectionIsOpen()
{
if(sqlConn==null)
{
sqlConn=newSqlConnection(this.connectionStr);
sqlConn.Open();
}
elseif(sqlConn.State==ConnectionState.Closed)
{
sqlConn.Open();
}
}
publicDBUtility(stringserver,stringdatabase,stringuid,stringpassword)
{
this.Server=server;
this.Database=database;
this.Uid=uid;
this.Password=password;
this.connectionStr="Server="+this.Server+";Database="+this.Database+";UserId="+this.Uid+";Password="+this.Password;
}
publicintExecuteNonQueryForMultipleScripts(stringsqlStr)
{
EnsureConnectionIsOpen();
SqlCommandcmd=sqlConn.CreateCommand();
cmd.CommandType=CommandType.Text;
cmd.CommandText=sqlStr;
returncmd.ExecuteNonQuery();
}
publicintExecuteNonQuery(stringsqlStr)
{
EnsureConnectionIsOpen();
SqlCommandcmd=newSqlCommand(sqlStr,sqlConn);
cmd.CommandType=CommandType.Text;
returncmd.ExecuteNonQuery();
}
publicobjectExecuteScalar(stringsqlStr)
{
EnsureConnectionIsOpen();
SqlCommandcmd=newSqlCommand(sqlStr,sqlConn);
cmd.CommandType=CommandType.Text;
returncmd.ExecuteScalar();
}
publicDataSetExecuteDS(stringsqlStr)
{
DataSetds=newDataSet();
EnsureConnectionIsOpen();
SqlDataAdaptersda=newSqlDataAdapter(sqlStr,sqlConn);
sda.Fill(ds);
returnds;
}
publicvoidDispose()
{
if(sqlConn!=null)
sqlConn.Close();
}
}
}
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
namespacePinkDatabaseSync
{
publicclassSQLDBSystemType
{
publicstaticDictionary
{
get{
varsystemTypeDict=newDictionary
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");
returnsystemTypeDict;
}
}
}
}
3.写个同步数据库表结构schema:
publicvoidSyncDBSchema(stringserver,stringdbname,stringuid,stringpassword,
stringserver2,stringdbname2,stringuid2,stringpassword2)
{
DBUtilitydb=newDBUtility(server,dbname,uid,password);
DataSetds=db.ExecuteDS("SELECTsobjects.nameFROMsysobjectssobjectsWHEREsobjects.xtype=‘U‘");
DataRowCollectiondrc=ds.Tables[0].Rows;
stringtest=string.Empty;
stringnewLine="";
foreach(DataRowdrindrc)
{
stringtableName=dr[0].ToString();
test+="ifNOTexists(select*fromsys.objectswherename=‘"+tableName+"‘andtype=‘u‘)";
test+="CREATETABLE[dbo].["+tableName+"]("+newLine;
DataSetds2=db.ExecuteDS("SELECT*FROMsys.columnsWHEREobject_id=OBJECT_ID(‘dbo."+tableName+"‘)");
DataRowCollectiondrc2=ds2.Tables[0].Rows;
foreach(DataRowdr2indrc2)
{
test+="["+dr2["name"].ToString()+"]";
stringtypeName=SQLDBSystemType.systemTypeDict[dr2["system_type_id"].ToString()];
test+="["+typeName+"]";
stringcharLength=string.Empty;
if(typeName.Contains("char"))
{
charLength=(Convert.ToInt32(dr2["max_length"].ToString())/2).ToString();
test+="("+charLength+")"+newLine;
}
boolisIdentity=bool.Parse(dr2["is_identity"].ToString());
test+=isIdentity?"IDENTITY(1,1)":string.Empty;
boolisNullAble=bool.Parse(dr2["is_nullable"].ToString());
test+=(isNullAble?
"NULL,":"NOTNULL,")+newLine;
}
test+="CONSTRAINT[PK_"+tableName+"]PRIMARYKEYCLUSTERED";
stringprimaryKeyName=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;
DBUtilitydb2=newDBUtility(server2,dbname2,uid2,password2);
db2.ExecuteNonQueryForMultipleScripts(test);
}
privatevoidSyncDB_Click(objectsender,EventArgse)
{
stringserver="localhost";
stringdbname="testdb1";
stringuid="sa";
stringpassword="password1";
stringserver2="servername2";
stringdbname2="testdb2";
stringuid2="sa";
stringpassword2="password2";
try
{
SyncDBSchema(server,dbname,uid,password,server2,dbname2,uid2,password2);
MessageBox.Show("Donesyncdbschemasuccessfully!");
}
catch(Exceptionexc)
{
MessageBox.Show(exc.ToString());
}
}
注:这仅仅是做个简单的DBschema同步。还能够非常多地方要继续完好,例如,约束。双主密钥。外键等。。
版权声明:本文博客原创文章。博客,未经同意,不得转载。