1 Private voidBtnback_click (Objectsender, EventArgs e)2 {3 stringSaveaway =@"C:\1.bak";4 //string cmdtext = @ "BACKUP Database" + system.configuration.configurationsettings.appsettings["dbName"] + "To disk=" + Saveaway + "'";5 stringCmdtext =@"Backup Database Testdemo to disk= '"+ Saveaway +"'";6Bakreductsql (Cmdtext,true);7 }8 9 Private voidBtnrestore_click (Objectsender, EventArgs e)//RecoveryTen { One //string openaway = This.tbxReductLoad.Text.ToString (). Trim ();//the path to the read file A stringOpenaway =@"C:\1.bak";//the path to the read file - //string cmdtext = @ "RESTORE Database" + system.configuration.configurationsettings.appsettings["dbName"] + "from dis k= ' "+ Openaway +" ' "; - stringCmdtext =@"Restore Database Testdemo from disk= '"+ Openaway +"' with REPLACE;"; theBakreductsql (Cmdtext,false); - } - /// <summary> - ///Backup and restore operations to the database, SQL statement implementation + /// </summary> - /// <param name= "Cmdtext" >SQL statement to implement backup or restore</param> + /// <param name= "Isbak" >whether the operation is a backup operation, is true no, is false</param> A Private voidBakreductsql (stringCmdtext,BOOLIsbak) at { -SqlCommand Cmdbakrst =NewSqlCommand (); -SqlConnection conn =NewSqlConnection ("Data Source=.;i Nitial Catalog=master;uid=sa;pwd=sa;"); - Try - { - Conn. Open (); inCmdbakrst.connection =Conn; -Cmdbakrst.commandtype =CommandType.Text; to if(!isbak)//if it is a recovery operation + { - stringSetoffline ="Alter Database Testdemo Set Offline with rollback immediate;"; the stringSetonline ="Alter Database Testdemo Set Online with Rollback immediate;"; *Cmdbakrst.commandtext = setoffline + Cmdtext +Setonline; $ }Panax Notoginseng Else - { theCmdbakrst.commandtext =Cmdtext; + } A cmdbakrst.executenonquery (); the if(!Isbak) + { -MessageBox.Show ("Congratulations, the data is successfully restored to the status of the selected document! ","System Messages"); $ } $ Else - { -MessageBox.Show ("Congratulations, you have successfully backed up your current data! ","System Messages"); the } - }Wuyi Catch(SqlException sexc) the { -MessageBox.Show ("failed, possibly due to database operation failure:"+ Sexc,"Database error Messages"); Wu } - Catch(Exception ex) About { $MessageBox.Show ("Sorry, the operation failed, possible cause:"+ EX,"System Messages"); - } - finally - { A cmdbakrst.dispose (); + Conn. Close (); the Conn. Dispose (); - } $}
Backup files are saved on the database server
C # Backup, restoring the database