This article main content source Stswordman introduction, the development environment is 10, the database is 08R2
The original address is http://www.cnblogs.com/stswordman/archive/2006/08/06/469002.html.
///
Backup method
///
SqlConnection conn = new SqlConnection ("server=.;D Atabase=master; User Id=sa; Password=sa; ");
SqlCommand CMDBK = new SqlCommand ();
Cmdbk.commandtype = CommandType.Text;
Cmdbk.connection = conn;
Cmdbk.commandtext = @ "BACKUP database test to disk= ' C:\ba ' with Init";
Try
{
Conn. Open ();
Cmdbk.executenonquery ();
MessageBox.Show ("Backup successed.");
}
catch (Exception ex)
{
MessageBox.Show (ex. Message);
}
Finally
{
Conn. Close ();
Conn. Dispose ();
}
///
Restore method
///
SqlConnection conn = new SqlConnection ("server=.;D Atabase=master; User Id=sa; Password=sa; Trusted_connection=false ");
Conn. Open ();
KILL DataBase Process
SqlCommand cmd = new SqlCommand ("Select spid from sysprocesses, sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid an D sysdatabases. Name= ' Test ', conn);
SqlDataReader Dr;
Dr = cmd. ExecuteReader ();
ArrayList list = new ArrayList ();
while (Dr. Read ())
{
List. ADD (Dr. GetInt16 (0));
}
Dr. Close ();
for (int i = 0; i < list. Count; i++)
{
cmd = new SqlCommand (string. Format ("KILL {0}", list), conn);
Cmd. ExecuteNonQuery ();
}
SqlCommand CMDRT = new SqlCommand ();
Cmdrt.commandtype = CommandType.Text;
Cmdrt.connection = conn;
Cmdrt.commandtext = @ "RESTORE database test from disk= ' C:\ba '";
Try
{
Cmdrt.executenonquery ();
MessageBox.Show ("Restore successed.");
}
catch (Exception ex)
{
MessageBox.Show (ex. Message);
}
Finally
{
Conn. Close ();
}
Because the database is installed separately on the server, so the file selected when the database recovery is troublesome, according to the user to provide ideas: in the database to create a separate backup file-file path table, used to record and display the data files backed up by users; When restoring from a database, the backup file-file path table is queried. For user selection and recovery, if the file does not exist (mistakenly deleted), prompts the user to delete the database record.
Unresolved issue: Records in database tables may not be consistent with actual backup files and database backups on the server cannot be removed (remote browsing as MS Database management is not possible).