Remote backup and recovery of SQL Server databases
Source: Internet
Author: User
/// < Summary >
/// Back up a database to a local disk
/// </ Summary >
Public Bool Backup (String backupfile)
{
Try
{
// Step 1: create a temporary folder on the server
Executesql (@ "master .. xp_cmdshell ' MD c: \ Temp ' ");
Executesql (@ "master .. xp_cmdshell ' Del c: \ temp \ *. */Q ' ");
// Step 2: Back up the database to the server directory
Executesql (@" Backup Database " + Databasename () + @" To Disk = ' C: \ temp \ hssy ' ");
// Step 3: Backup Directory of the Shared Server
Executesql (@ "master .. xp_cmdshell ' NET Share sqldataback = c: \ Temp ' ");
// Step 4: copy the backup file on the server to the local device
File . Copy (@"\\" + Serverip () + @ "\ Sqldataback \ hssy", backupfile, true );
Return True;
}
Catch (system. Data. sqlclient. sqlexception E)
{
Throw new exception (E. Message );
}
Finally
{
// Step 5: Cancel sharing the server shared directory
Executesql (@ "master .. xp_cmdshell ' NET Share sqldataback/delete ' ");
}
}
/// < Summary >
/// Recover a database from a local disk
/// </ Summary >
Public Bool Restore (String restorefile)
{
Try
{
// Step 1: Shut down the user process to prevent other users from using the database, resulting in data recovery failure
Killserveruser ();
// Step 1: create a temporary folder on the server
Executesql (@ "master .. xp_cmdshell ' MD c: \ Temp ' ");
Executesql (@ "master .. xp_cmdshell ' Del c: \ temp \ *. */Q ' ");
// Step 2: Restore directory of the Shared Server
Executesql (@ "master .. xp_cmdshell ' NET Share sqlrestore = c: \ Temp ' ");
// Step 3: copy the backup file on the server to the local device
File . Copy (restorefile ,@"\\" + Serverip () + @ "\ Sqlrestore \ hssy", true );
// Step 4: Cancel sharing the server shared directory
Executesql (@ "master .. xp_cmdshell ' NET Share sqldataback/delete ' ");
// Step 5: Restore the database to the server directory
Executesql (@" Restore Database " + Databasename () + @" From Disk = ' C: \ temp \ hssy ' ");
Return True;
}
Catch (system. Data. sqlclient. sqlexception E)
{
Throw new exception (E. Message );
}
Finally
{
// Step 6: Cancel sharing the server shared directory
// Dbhelpersql. executesql (@ "master .. xp_mongoshell ' NET Share sqldataback/delete ' ");
}
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.