Here, we well introduce a way to backup and recover database in C#: use SQL DMO.
Most SQL Server administrative tasks are programmable thanks to a set of objects known as SQL-DMO. Distributed Management Objects (DMO) is a set of programmable objects that come with SQL Server that make it easy to programmatically administer your databases. SQL-DMO is actually the foundation of Enterprise Manager, so you can pretty much do anything programmatically that you can do in the management tools. Some of these tasks include:
•1. Scripting Objects
•2. Backing up databases
•3. Creating jobs
•4. Altering tables
5. Recover database
… … much more.
SQLDMO is from SQL.DLL of Microsoft SQL Server. Because SQL.DLL is a com object, we had to add the reference to SQL.DLL in .net before it was used.
So, we start to introduce a class written in C#, which is used to backup and recover the Microsoft SQL Server:
using System;
namespace DbService
{
///
/// DbOper Object , primarily use SQLDMO to backup and recover Microsoft SQL Server database ///
public sealed class DbOper
{
///
/// the constructor of the object DbOper
///
private DbOper()
{
}
///
/// backup database
///
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 = “Recover Database”;
oBackup.Initialize = true;
oBackup.SQLBackup(oSQLServer);
}
catch
{
throw;
}
finally
{
oSQLServer.DisConnect();
}
}
///
/// Recover Database
///
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();
}
}
}
}