Use sqldmo to back up and restore Microsoft SQL Server databases
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 a sqldmo provided by Microsoft SQL Server. DLL provided, because sqldmo. DLL is a COM object, so before using it, you must. add a reference to it in the. NET project, as shown in:
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
/// </Summary>
Public sealed class dboper
{
/// <Summary>
/// Dboper Constructor
/// </Summary>
Private dboper ()
{
}
/// <Summary>
/// Database Backup
/// </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 = "database backup ";
Obackup. initialize = true;
Obackup. sqlbackup (osqlserver );
}
Catch
{
Throw;
}
Finally
{
Osqlserver. Disconnect ();
}
}
/// <Summary>
/// Restore the database
/// </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 ();
}
}
}
}