Use SQLDMO in C # To back up and restore a Microsoft SQL Server database
SQLDMO (SQL Distributed Management Objects, SQL Distributed Management object) encapsulates Objects in the Microsoft SQL Server database. SQLDMO is the application interface used by the enterprise manager in Microsoft SQL Server. Therefore, it can perform many functions, including database backup and recovery.
SQLDMO is provided by SQLDMO. dll of Microsoft SQL Server. Because SQLDMO. dll is a COM object, you must add references to it in the. NET project before using SQLDMO. dll.
The following is a class written in C # for Microsoft SQL Server database backup and recovery:
Using System;
Namespace DbService
{
/// <: Summary>
/// DbOper class, mainly using SQLDMO to back up and restore the Microsoft SQL Server database
///
Public sealed class DbOper
{
/// <: Summary>
/// DbOper Constructor
///
Private DbOper ()
{
}
/// <: Summary>
/// Database Backup
///
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 = "database backup ";
OBackup. Initialize = true;
OBackup. SQLBackup (oSQLServer );
}
Catch
{
Throw;
}
Finally
{
OSQLServer. DisConnect ();
}
}
/// <: Summary>
/// Restore the 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 ();
}
}
}
}
Although this code is very short, it is very practical and I hope it will help you.