This question puzzled me a long time, searches on the net, also did not have the complete solution, is not too simple, is to utter nonsense, some forum still no one answers this question. Today I completely solve this problem and test it completely through in C #. Now write him out, hope to help friends (if you want to reprint, remember to give me copyright OH.) Hey!!! ). The following information is integrated online and my actual problems are sorted out.
Backup:
Write in the backup button:
Copy Code code as follows:
protected void Button1_Click (object sender, EventArgs e)
{
String path = "E:\\maz database backup \" + menu+ ". Bak";
if (file.exists (path))
{
File.delete (path); Note that this step is important, if repeated, in the backed-up data, it will become,
The data you just started, so you have to delete it every time.
}
if (! File.exists (PATH))
{
FileStream fs = file.create (path);
Fs. Close ();
}
String backupstr= "Backup database Test to disk= ' +path+ ';";
SqlConnection con = new SqlConnection ("SERVER=LOCALHOST;DATABASE=MENU;UID=SA;PWD=SA;");
SqlCommand cmd = new SqlCommand (Backupstr, con);
Try
{
Con. Open ();
Cmd. ExecuteNonQuery ();
MessageBox.Show ("Backup successful!") ");
Connection. Close ();
}
catch (Exception ex)
{
String stringerror = ex. ToString ();
MessageBox.Show ("Backup failed!") ");
Connection. Close ();
}
}
Restores:
Write in the Restore button:
Copy Code code as follows:
protected void button2_click (object sender, EventArgs e)
{
String path = "E:\\maz database backup \" + menu+ ". Bak";
String connectionstringtest = "Server=localhost;d atabase=master;uid=sa;pwd=sa";
SqlConnection connection = new SqlConnection (Connectionstringtest);
String backupstr = "RESTORE Database Menu from disk= '" + Path + "';";
Try
{
String sql = "Exec killspid '" + menu+ "'";//This is critical, or there will be a mistake on the subject.
SqlCommand cmd = new SqlCommand (sql, connection);
Connection. Open ();
Cmd. ExecuteNonQuery ();
cmd = new SqlCommand (backupstr, connection);
Cmd. ExecuteNonQuery ();
MessageBox.Show ("Restore success!") ");
Connection. Close ();
}
catch (Exception ex)
{
String stringerror = ex. ToString ();
MessageBox.Show ("Recovery failed!") ");
Connection. Close ();
}
}
Stored Procedures Killspid
Copy Code code as follows:
Create proc killspid (@dbname varchar (20))
As
Begin
declare @sql nvarchar (500)
DECLARE @spid int
Set @sql = ' Declare getspid cursor for
Select spid from sysprocesses where dbid=db_id (' + @dbname + ') '
EXEC (@sql)
Open Getspid
FETCH NEXT from Getspid into @spid
While @ @fetch_status <>-1
Begin
EXEC (' kill ') + @spid
FETCH NEXT from Getspid into @spid
End
Close Getspid
Deallocate getspid
End