在上一篇周公簡單講述了SMO的一些基本概念,實際上SMO體繫結構遠不止周公在上一篇中講述的那麼簡單,是MSDN上給出的一個完整的結構圖:
是一個完整的涉及到各種關係的結構圖。不過它們之間的階層關係周公已經在上一篇做了簡單概述。
在本篇中周公還是在上一篇的基礎上再做稍微深入一點的介紹,在本篇中主要講述如何擷取資料庫常見對象資訊,並且如何利用SMO來進行一些日常操作:如建立Login,建立資料庫、備份資料庫和還原資料庫。執行上面這些操作的SQL語句也許我們已經寫過,下面我們來看看利用SMO來操作的代碼將如何寫。為了便於理解,在代碼中的注釋比較詳盡,所以本篇中代碼之外的講解就不多了。另外,需要注意的是SMO的dll的版本隨著升級變化比較大,這一點不同.NET Framework,沒有考慮向下相容。
代碼如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.SqlServer.Management.Smo.RegisteredServers;//在microsoft.sqlserver.smo.dll中using Microsoft.SqlServer.Management.Smo;//需添加microsoft.sqlserver.smo.dll的引用using Microsoft.SqlServer.Management.Common;//需添加microsoft.sqlserver.connectioninfo.dll的引用namespace SSISStudy{ /// <summary> /// SQL Server編程些列文章(2):SMO常用對象的有關操作 /// 作者:周公 /// 建立日期:2012-05-23 /// 部落格地址:http://blog.csdn.net/zhoufoxcn http://zhoufoxcn.blog.51cto.com /// 新浪微博地址:http://weibo.com/zhoufoxcn class SMODemo02 { /// <summary> /// 顯示資料庫常見對象資訊樣本,本方法中的代碼只針對9.0版本的SMO dll(SQL2005附帶程式集) /// </summary> public static void ShowSMOObjects() { Console.WriteLine("Server Group Information"); foreach (ServerGroup serverGroup in SmoApplication.SqlServerRegistrations.ServerGroups) { Console.WriteLine("Group Name:{0},Path:{1},ServerType:{2},State:{3},Urn:{4}", serverGroup.Name, serverGroup.Path, serverGroup.ServerType, serverGroup.State, serverGroup.Urn); } Console.WriteLine("Registered Server Information"); foreach (RegisteredServer regServer in SmoApplication.SqlServerRegistrations.RegisteredServers) { Console.WriteLine("Server Name:{0},Login:{1},State:{2},Urn:{3}", regServer.Name, regServer.Login, regServer.State, regServer.Urn); } //建立ServerConnection的執行個體 ServerConnection connection = new ServerConnection(); //指定連接字串 connection.ConnectionString = "Data Source=goodapp;Initial Catalog=master;User ID=sa;Password=root;"; //執行個體化Server Server server = new Server(connection); Console.WriteLine("ActiveDirectory:{0},InstanceName:{1}", server.ActiveDirectory, server.InstanceName); //下面列出每個資料庫的具體資訊 foreach (Database db in server.Databases) { Console.WriteLine("Database Name:{0},ActiveDirectory:{1},ActiveConnections:{2},DataSpaceUsage:{3},PrimaryFilePath:{4}", db.Name, db.ActiveDirectory, db.ActiveConnections, db.DataSpaceUsage, db.PrimaryFilePath); //列出資料庫的資料檔案檔案組資訊 foreach (FileGroup fileGroup in db.FileGroups) { Console.WriteLine("\tFileGroup Name:{0},Size:{1},State:{2},Urn:{3}", fileGroup.Name, fileGroup.Size, fileGroup.State, fileGroup.Urn); //列出每個檔案組中的資料檔案資訊 foreach (DataFile dataFile in fileGroup.Files) { Console.WriteLine("\t\tDataFile Name:{0},Size:{1},State:{2},Urn:{3},FileName:{4}", dataFile.Name, dataFile.Size, dataFile.State, dataFile.Urn, dataFile.FileName); } } //列出資料庫記錄檔資訊 foreach (LogFile logFile in db.LogFiles) { Console.WriteLine("\tLogFile Name:{0},Size:{1},State:{2},Urn:{3},FileName:{4}", logFile.Name, logFile.Size, logFile.State,logFile.Urn,logFile.FileName); } } } /// <summary> /// 利用SMO建立SQL登入 /// </summary> public static void CreateLogin() { string loginName = "zhoufoxcn";//要建立的資料庫登入名稱 string loginPassword = "C#.NET";//登入密碼 //建立ServerConnection的執行個體 ServerConnection connection = new ServerConnection(); //指定連接字串 connection.ConnectionString = "Data Source=goodapp;Initial Catalog=master;User ID=sa;Password=root;"; //執行個體化Server Server server = new Server(connection); #region [建立資料庫登入對象] //檢查在資料庫是否已經存在該登入名稱 var queryLogin = from Login temp in server.Logins where string.Equals(temp.Name, loginName, StringComparison.CurrentCultureIgnoreCase) select temp; Login login = queryLogin.FirstOrDefault<Login>(); //如果存在就刪除 if (login != null) { login.Drop(); } login = new Login(server, loginName); login.LoginType = LoginType.SqlLogin;//指定登入方式為SQL認證 login.PasswordPolicyEnforced = true; login.DefaultDatabase = "master";//預設資料庫 login.Create(loginPassword); #endregion } /// <summary> /// 利用SMO建立資料庫 /// </summary> public static void CreateDatabase() { string databaseName = "SMODemo"; //建立ServerConnection的執行個體 ServerConnection connection = new ServerConnection(); //指定連接字串 connection.ConnectionString = "Data Source=goodapp;Initial Catalog=master;User ID=sa;Password=root;"; //執行個體化Server Server server = new Server(connection); #region [建立資料庫物件] //檢查在資料庫是否已經存在該資料庫 var queryDatabase = from Database temp in server.Databases where string.Equals(temp.Name, databaseName, StringComparison.CurrentCultureIgnoreCase) select temp; Database database = queryDatabase.FirstOrDefault<Database>(); //如果存在就刪除 if (database != null) { database.Drop(); } database = new Database(server, databaseName); //指定資料庫資料檔案細節 FileGroup fileGroup = new FileGroup { Name = "PRIMARY", Parent = database, IsDefault = true }; DataFile dataFile = new DataFile { Name = databaseName + "_data", Parent = fileGroup, FileName = @"F:\SQLData2005\" + databaseName + ".mdf" }; fileGroup.Files.Add(dataFile); //指定資料庫記錄檔細節 LogFile logFile = new LogFile { Name = databaseName + "_log", Parent = database, FileName = @"F:\SQLData2005\" + databaseName + ".ldf" }; database.FileGroups.Add(fileGroup); database.LogFiles.Add(logFile); database.Create(); #endregion } /// <summary> /// 利用SMO備份資料庫 /// </summary> public static void BackupDatabase() { string databaseName = "msdb";//備份的資料庫名 string bkPath = @"C:\";//存放備份後的資料的檔案夾 //建立ServerConnection的執行個體 ServerConnection connection = new ServerConnection(); //指定連接字串 connection.ConnectionString = "Data Source=goodapp;Initial Catalog=master;User ID=sa;Password=root;"; //執行個體化Server Server server = new Server(connection); #region [建立Database Backup對象] Backup backup = new Backup(); backup.Action = BackupActionType.Database;//完全備份 backup.Database = databaseName; backup.BackupSetDescription = "Full backup of master"; backup.BackupSetName = "master Backup"; //建立備份裝置 BackupDeviceItem bkDeviceItem = new BackupDeviceItem(); bkDeviceItem.DeviceType = DeviceType.File; bkDeviceItem.Name = bkPath+databaseName+".bak"; backup.Devices.Add(bkDeviceItem); backup.Incremental = false; backup.LogTruncation = BackupTruncateLogType.Truncate; backup.SqlBackup(server); #endregion } /// <summary> /// 備份資料庫 /// </summary> public static void RestoreDatabase() { string databaseName = "SMODemo";//備份的資料庫名 string bkPath = @"C:\";//存放備份後的資料的檔案夾 //建立ServerConnection的執行個體 ServerConnection connection = new ServerConnection(); //指定連接字串 connection.ConnectionString = "Data Source=goodapp;Initial Catalog=master;User ID=sa;Password=root;"; //執行個體化Server Server server = new Server(connection); Restore restore = new Restore(); restore.NoRecovery = false; restore.NoRewind = false; restore.Action = RestoreActionType.Database; restore.Database = databaseName; //建立備份裝置 BackupDeviceItem bkDeviceItem = new BackupDeviceItem(); bkDeviceItem.DeviceType = DeviceType.File; bkDeviceItem.Name = bkPath + databaseName + ".bak"; //如果需要重新制定Restore後的資料庫的物理檔案位置,需要知道資料庫檔案的邏輯檔案名稱 //可以RESTORE FILELISTONLY 來列出邏輯檔案名稱,如果覆蓋已有資料庫可以通過SMO來擷取 //因本處使用的是剛剛備份的msdb資料庫來Restore,所以其分別為"MSDBData"和"MSDBLog" //如果不指定Restore路徑則預設恢複到資料庫伺服器存放資料的檔案夾下 RelocateFile relocateDataFile = new RelocateFile { LogicalFileName = "MSDBData", PhysicalFileName = bkPath + databaseName + ".mdf" };//(databaseName + "_data", bkPath + databaseName + ".mdf"); RelocateFile relocateLogFile = new RelocateFile { LogicalFileName = "MSDBLog", PhysicalFileName = bkPath + databaseName + ".ldf" };//(databaseName + "_log", bkPath + databaseName + ".ldf"); restore.Devices.Add(bkDeviceItem); restore.RelocateFiles.Add(relocateDataFile); restore.RelocateFiles.Add(relocateLogFile); restore.SqlRestore(server); } }}
執行結果在這裡就不貼圖了,反正是是在周公家裡的中文環境和辦公室英文環境中測試通過。預先透漏一下,下一篇將講述如何擷取SQL Server的對象的建立SQL語句,比如表、預存程序、函數等。
2012-05-23
周公