public void backup() { SqlConnection conn = new SqlConnection("Server=.;Database=master;User ID=sa;Password=1q2w3e4r"); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.Connection = conn; cmd.CommandText = @"backup database testBackUp to disk=‘D:backupdb‘ with init "; try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception e) { //throw; } finally { conn.Close(); conn.Dispose(); } } public void restore() { SqlConnection conn = new SqlConnection("Server=.;Database=master;User ID=sa;Password=1q2w3e4r;Trusted_Connection=False"); conn.Open(); SqlCommand cmd = new SqlCommand("SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name=‘testBackUp‘", conn); SqlDataReader 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[i]), conn); cmd.ExecuteNonQuery(); } SqlCommand c = new SqlCommand(); c.CommandType = CommandType.Text; c.Connection = conn; //with REPLACE very important c.CommandText = @"restore database testBackUp from disk=‘D:backupdb‘ with REPLACE"; try { c.ExecuteNonQuery(); } catch (Exception e) { //throw; } finally { conn.Close(); } }
时间: 2024-10-09 21:26:15