.Net 数据库(SqlServer2008)的备份、还原

//备份代码
private
void Backup() { SqlConnection sqlConn = new SqlConnection(strConn); strFileName = "databasebackup_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".bak"; strFile = strPath + strFileName; strSql = "BACKUP DATABASE TeamWeb to DISK ='" + strFile + "'"; SqlCommand sqlCmd = new SqlCommand(strSql, sqlConn); Maticsoft.Model.T_DataBaseBackUpInfo model = new Maticsoft.Model.T_DataBaseBackUpInfo(); Maticsoft.BLL.T_DataBaseBackUpInfo bll = new Maticsoft.BLL.T_DataBaseBackUpInfo(); model.Name = strFileName; model.PostTime = DateTime.Now; try { sqlConn.Open(); sqlCmd.ExecuteNonQuery(); bll.Add(model); jc = new JsonClass("备份成功", 1); sqlConn.Close(); } catch (Exception ex) { jc = new JsonClass("备份失败",2); } Response.Write(jc); Response.End(); }
//还原代码
private
void Restore(int id) { Maticsoft.Model.T_DataBaseBackUpInfo model = new Maticsoft.Model.T_DataBaseBackUpInfo(); Maticsoft.BLL.T_DataBaseBackUpInfo bll = new Maticsoft.BLL.T_DataBaseBackUpInfo(); model = bll.GetModel(id); SqlConnection conn = new SqlConnection("Server=localhost;Database=master;User ID=sa;Password=123456;Trusted_Connection=False"); conn.Open(); try { //KILL DataBase Process SqlCommand cmd = new SqlCommand("SELECT spid FROM SysProcesses ,Master.dbo.sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='TeamWeb'", 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++) { object num = list[i]; cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn); cmd.ExecuteNonQuery(); } string strfile = System.Web.HttpContext.Current.Server.MapPath("../Backup/") + model.Name; strSql = "use master restore database TeamWeb from disk='" + strfile + "' with replace "; SqlCommand sqlCmd = new SqlCommand(strSql, conn); sqlCmd.ExecuteNonQuery(); jc = new JsonClass("还原成功", 1); conn.Close(); SqlConnection.ClearAllPools();//还原成功后,加上这句话,再次访问数据库,就不会报:在向服务器发送请求时发生传输级错误。 } catch (Exception ex) { jc = new JsonClass("还原失败", 2); } Response.Write(jc); Response.End(); }

 

posted on 2013-12-15 22:30  赤豆元宵  阅读(263)  评论(0编辑  收藏  举报

导航