The recent ASP. Net project requires the database backup function. After studying the code on the Internet, we will share with you the implementation methods and issues needing attention.
1. first add InterOP. sqldmo. DLL reference (if you want to directly write the backup code on the page, you can directly reference it on the web. If you want to write a class library, you must add it under the class library project ).
2. The following uses a class library project as an example:
Add the dboperator class and add the following code:
Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. Data. sqlclient;
/// <Summary>
/// Summary of dboperater
/// </Summary>
Public class dboperater
{
Public dboperater ()
{
// F Constructor
}
// Database Backup
Public static string dbbackup (string dbname, string backupdbname)
{
Sqldmo. Backup obackup = new sqldmo. backupclass ();
Sqldmo. sqlserver osqlserver = new sqldmo. sqlserverclass ();
Try
{
Osqlserver. loginsecure = false;
// The IP address is the address of the database server.
Osqlserver. Connect ("127.0.0.1", "sa", "sa ");
Obackup. Action = sqldmo. sqldmo_backup_type.sqldmobackup_database;
Obackup. Database = dbname;
// This path is the absolute address under the Database Server
Obackup. Files = @ "E: // back //" + backupdbname + ". Bak ";
Obackup. backupsetname = backupdbname;
// Description
Obackup. backupsetdescription = "database backup ";
Obackup. initialize = true;
// Start backup
Obackup. sqlbackup (osqlserver );
// Return the prompt statement
Return "the database has been backed up to [" + obackup. Files + "]";
}
Catch (exception ex)
{
Throw new exception ("database backup failed:" + ex. Message );
}
Finally
{
Osqlserver. Disconnect ();
}
}
}
3. Call the dboperator. dbbackup () method on the page. Note that the input parameter dbname is the database name and backupdbname is the backup name.
4. pay special attention to "E: // back //" + backupdbname + ". bak "this address is the address on the database server, not the address on the server where the page project is located. Of course, it doesn't matter if your project is on one server.
5. if the project is on the same server as the database, "osqlserver. connect ("127.0.0.1", "sa", "sa"); "write the IP address here ". ". Otherwise, an error may occur.