C#操作数据库还原bak文件 删除操作
/// <summary> /// 还原数据库 /// </summary> /// <param name="dataBaseName">数据库名称</param> /// <param name="path">还原的路径bak文件</param> /// <param name="UserId">用户名</param> /// <param name="PassWord">密码</param> /// <param name="DataSource">IP或者当前服务(.)</param> public static void Restoredb(string dataBaseName, string path, string userId, string passWord, string dataSource) { var strconn = "Data Source=" + dataSource + ";Initial Catalog=master;User ID=" + userId + ";pwd =" + passWord + ""; DataTable DBNameTable = new DataTable(); SqlDataAdapter Adapter = new SqlDataAdapter("select name from master..sysdatabases", strconn); lock (Adapter) { Adapter.Fill(DBNameTable); } foreach (DataRow row in DBNameTable.Rows) { if (row["name"].ToString() == dataBaseName) { throw new KnownException("已存在对应的数据,请勿重复还原数据库!"); } }
//检测真正当前bak文件真正的log mdf的名字 var strsql = " restore filelistonly from disk = '" + path + "'"; SqlDataAdapter Adapter2 = new SqlDataAdapter(strsql, strconn); var dt = new DataTable(); lock (Adapter2) { Adapter2.Fill(dt); } var mdf = dt.Rows[0][0].ToString(); var log = dt.Rows[1][0].ToString(); string restore = string.Format(@"restore database {0} from disk = '{1}' with REPLACE , move '{2}' to 'D:\{3}.mdf' ,move '{4}' to 'D:\{5}.ldf'", dataBaseName, path, mdf, dataBaseName, log, dataBaseName); SqlConnection conn = new SqlConnection(strconn); SqlCommand cmd1 = new SqlCommand(restore, conn); conn.Open();//k cmd1.ExecuteNonQuery(); conn.Close();//g } /// <summary> /// 删除数据库 /// </summary> /// <param name="dataBaseName"></param> /// <param name="UserId"></param> /// <param name="PassWord"></param> /// <param name="DataSource"></param> /// <param name="code"></param> /// <returns></returns> public static void DeleteDataBase(string dataBaseName, string userId, string passWord, string dataSource) { var strconn = "Data Source=" + dataSource + ";Initial Catalog=master;User ID=" + userId + ";pwd =" + passWord + ""; SqlConnection conn = new SqlConnection(strconn);//创建一个数据库连接对象 conn.Open(); var strsql = string.Format("drop database {0}", dataBaseName); SqlCommand cmd = new SqlCommand(strsql, conn); cmd.ExecuteNonQuery(); try { cmd.ExecuteNonQuery(); } catch (Exception ex) { throw new KnownException(ex.Message); } finally { conn.Close();//g } }