明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線(xiàn)學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

在C#中使用SQLDMO備份與恢復(fù)Microsoft SQL Server數(shù)據(jù)庫(kù)

[摘要]在C#中運(yùn)用SQLDMO備份和恢復(fù)Microsoft SQL Server數(shù)據(jù)庫(kù) SQLDMO(SQL Distributed Management Objects,SQL分布式管理對(duì)象)...
在C#中運(yùn)用SQLDMO備份和恢復(fù)Microsoft SQL Server數(shù)據(jù)庫(kù)

SQLDMO(SQL Distributed Management Objects,SQL分布式管理對(duì)象)封裝了Microsoft SQL Server數(shù)據(jù)庫(kù)中的對(duì)象。SQLDMO是Microsoft SQL Server中企業(yè)管理器所使用的應(yīng)用程序接口,所以它可以執(zhí)行很多功能,其中當(dāng)然也包括對(duì)數(shù)據(jù)庫(kù)的備份和恢復(fù)。

SQLDMO由Microsoft SQL Server自帶的SQLDMO.dll提供,由于SQLDMO.dll是一個(gè)COM對(duì)象,所以大家在用之前必須在.NET項(xiàng)目中添加對(duì)它的引用,如下圖所示:



下面是用C#語(yǔ)言書(shū)寫(xiě)的用于Microsoft SQL Server數(shù)據(jù)庫(kù)備份和恢復(fù)的類(lèi):

using System;

namespace DbService
{
/// <summary>
/// DbOper類(lèi),主要應(yīng)用SQLDMO實(shí)現(xiàn)對(duì)Microsoft SQL Server數(shù)據(jù)庫(kù)的備份和恢復(fù)
/// </summary>
public sealed class DbOper
{
/// <summary>
/// DbOper類(lèi)的構(gòu)造函數(shù)
/// </summary>
private DbOper()
{
}

/// <summary>
/// 數(shù)據(jù)庫(kù)備份
/// </summary>
public static void DbBackup()
{
SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
oSQLServer.LoginSecure = false;
oSQLServer.Connect("localhost", "sa", "1234");
oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackup.Database = "Northwind";
oBackup.Files = @"d:\Northwind.bak";
oBackup.BackupSetName = "Northwind";
oBackup.BackupSetDescription = "數(shù)據(jù)庫(kù)備份";
oBackup.Initialize = true;
oBackup.SQLBackup(oSQLServer);
}
catch
{
throw;
}
finally
{
oSQLServer.DisConnect();
}
}

/// <summary>
/// 數(shù)據(jù)庫(kù)恢復(fù)
/// </summary>
public static void DbRestore()
{
SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
oSQLServer.LoginSecure = false;
oSQLServer.Connect("localhost", "sa", "1234");
oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
oRestore.Database = "Northwind";
oRestore.Files = @"d:\Northwind.bak";
oRestore.FileNumber = 1;
oRestore.ReplaceDatabase = true;
oRestore.SQLRestore(oSQLServer);
}
catch
{
throw;
}
finally
{
oSQLServer.DisConnect();
}
}
}
}

這段代碼雖然很短,但是卻很實(shí)用,希望能夠?qū)Υ蠹矣兴鶐椭?)