The name of the database in this document is Projectcontrol
public static SqlConnection conn = new SqlConnection ("server= (local); Uid=sa;pwd=000;database=projectcontrol");
Back up public bool BackupDatabase (string databasefile) {if (! File.exists (Databasefile)) {}//restored database mydatabase String sql = "BACKUP databas E "+" Projectcontrol "+" to DISK = ' "+ databasefile +". Bak "; Conn. Open (); SqlCommand comm = new SqlCommand (SQL, conn); Comm.commandtype = CommandType.Text; try {Comm. ExecuteNonQuery (); } catch (Exception err) {string str = err. Message; MessageBox.Show (str); Conn. Close (); return false; } MessageBox.Show ("Backup succeeded"); Conn. Close ();//Shutdown database connection return true; }//Restore public string Restoredatabase (string backfile) {///Kill all the original database connection processes Sqlco Nnection conn = new SqlConnection (); Conn. ConnectionString = "Data source=.;i Nitial CatalOg=master; User ID=SA;PWD = 000 "; Conn. Open (); String sql = "Select spid from sysprocesses, sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid and sysdatabases. Name= ' "+" Projectcontrol "+" "; SqlCommand cmd1 = new SqlCommand (SQL, conn); SqlDataReader Dr; ArrayList list = new ArrayList (); try {dr = Cmd1. ExecuteReader (); while (Dr. Read ()) {list. ADD (Dr. GetInt16 (0)); } Dr. Close (); } catch (SqlException eee) {MessageBox.Show (eee. ToString ()); } finally {Conn. Close (); }//messagebox.show (list. Count.tostring ()); for (int i = 0; i < list. Count; i++) {Conn. Open (); CMD1 = new SqlCommand (string. Format ("KILL {0}", List[i]. TostrING ()), conn); Cmd1. ExecuteNonQuery (); Conn. Close (); MessageBox.Show ("The system has purged the database thread:" + list[i]. ToString () + "\ r \ n Restoring the database!" "); }//This must be the master database, not the database to be restored, because this becomes a process that has other processes//occupies the database. string constr = @ "Data source=.;i Nitial Catalog=master; User id=sa;pwd =tc0001 "; string database = "Projectcontrol"; string path = Backfile; String BACKUP = String.Format ("RESTORE database {0} from DISK = ' {1} ' with REPLACE ', DATABASE, Path); SqlConnection con = new SqlConnection (CONSTR); SqlCommand cmd = new SqlCommand (BACKUP, con); Con. Open (); try {cmd. ExecuteNonQuery (); MessageBox.Show ("Restore succeeded, click to exit the System!") "); Application.exit (); } catch (SqlException ee) {//throw (EE); MessageBox.Show ("Restore Failed"); MessageBox.Show (EE.ToString ()); } finally {con. Close (); } return "string of success or not"; }
Backup and restore of sqlsever2008 database