SQL Distributed Management Objects (SQL-DMO) 封裝 SQL Server 管理物件,企業管理器即建構於此。透過 SQLDMO.dll (COM 組件) 可程式化執行備份、還原、建立資料庫等管理工作。
使用前需在專案「加入參考」→ COM 標籤選擇 Microsoft SQLDMO Object Library。
using System;
using SQLDMO; // 需參考 SQLDMO.dll
namespace DbService
{
public sealed class DbOper
{
private DbOper() { } // 靜態類別模式
/// 完整資料庫備份
public static void DbBackup()
{
Backup oBackup = new BackupClass();
SQLServer oServer = new SQLServerClass();
try
{
oServer.LoginSecure = false; // SQL Server 驗證
oServer.Connect("localhost", "sa", "1234"); // 實際請從設定檔讀取
oBackup.Action = SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackup.Database = "Northwind";
oBackup.Files = @"d:\Northwind.bak";
oBackup.BackupSetName = "Northwind";
oBackup.BackupSetDescription = "資料庫備份";
oBackup.Initialize = true; // 覆寫現有備份檔
oBackup.SQLBackup(oServer);
}
catch { throw; }
finally { oServer.DisConnect(); }
}
/// 資料庫還原
public static void DbRestore()
{
Restore oRestore = new RestoreClass();
SQLServer oServer = new SQLServerClass();
try
{
oServer.LoginSecure = false;
oServer.Connect("localhost", "sa", "1234");
oRestore.Action = SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
oRestore.Database = "Northwind";
oRestore.Files = @"d:\Northwind.bak";
oRestore.FileNumber = 1; // 備份集編號
oRestore.ReplaceDatabase = true; // 允許覆蓋現有資料庫
oRestore.SQLRestore(oServer);
}
catch { throw; }
finally { oServer.DisConnect(); }
}
}
}
| 屬性 | 用途 |
|---|---|
| Action | 指定操作類型:Database/Files/Log |
| Database | 目標資料庫名稱 |
| Files | 備份檔完整路徑 |
| Initialize | true=覆寫備份檔,false=附加 |
| FileNumber | 備份檔內第幾組備份集 (通常為 1) |
| ReplaceDatabase | true=允許還原覆蓋現有 DB |
Relocate)。sysadmin 或 db_backupoperator/dbcreator 角色權限。