C#操作数据库还原bak文件 删除操作

         /// 
        /// 还原数据库
        /// 
        /// 数据库名称
        /// 还原的路径bak文件
        /// 用户名
        /// 密码
        /// IP或者当前服务(.)
        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 } /// /// 删除数据库 /// /// /// /// /// /// /// 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 } }

 

转载于:https://www.cnblogs.com/hbh123/p/9566227.html

你可能感兴趣的:(数据库,c#)