风暴烈酒辰

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
        /// <summary>
        /// 还原数据库
        /// </summary>
        /// <param name="strDbName">还原后的数据库名称</param>
        /// <param name="strFileName">数据库备份文件</param>
        /// <param name="dbDataName">源数据库文件</param>
        /// <param name="dbLogName">源数据库Log文件</param>
        /// <param name="dbPath">还原后保存的地址</param>
        /// <param name="serverName">服务器地址</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public static bool RestoreDB(string strDbName, string strFileName,string dbDataName,string dbLogName,string dbPath, string serverName, string userName, string password)
        {

            SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
            try
            {
                svr.Connect(serverName, userName, password);
                SQLDMO.QueryResults qr = svr.EnumProcesses(-1);
                int iColPIDNum = -1;
                int iColDbName = -1;
                for (int i = 1; i <= qr.Columns; i++)
                {
                    string strName = qr.get_ColumnName(i);
                    if (strName.ToUpper().Trim() == "SPID")
                    {
                        iColPIDNum = i;
                    }
                    else if (strName.ToUpper().Trim() == "DBNAME")
                    {
                        iColDbName = i;
                    }
                    if (iColPIDNum != -1 && iColDbName != -1)
                        break;
                }

                for (int i = 1; i <= qr.Rows; i++)
                {
                    int lPID = qr.GetColumnLong(i, iColPIDNum);
                    string strDBName = qr.GetColumnString(i, iColDbName);
                    if (strDBName.ToUpper() == strDbName.ToUpper())
                        svr.KillProcess(lPID);
                }

                SQLDMO.Restore res = new SQLDMO.RestoreClass();
                res.Action = 0;
                res.Files = strFileName;
                res.RelocateFiles = @"[" + dbDataName + "],[" + System.IO.Path.Combine(dbPath, strDbName + "_Data.mdf") + "],[" + dbLogName + "],[" + System.IO.Path.Combine(dbPath, strDbName + "_log.ldf") + "]";
                res.Database = strDbName;
                res.ReplaceDatabase = true;
                res.SQLRestore(svr);
                return true;
            }
            catch (Exception err)
            {
                throw (new Exception("恢复数据库失败,请关闭所有和该数据库连接的程序!" + err.Message));
            }
            finally
            {
                svr.DisConnect();
            }
        }

需要引用COM里的SQLDMO

posted on 2013-04-17 22:22  风暴烈酒辰  阅读(467)  评论(0编辑  收藏  举报