亲宝软件园·资讯

展开

sqlserver备份还原数据库 sqlserver备份还原数据库功能封装分享

人气:0
想了解sqlserver备份还原数据库功能封装讲解的相关内容吗,在本文为您仔细讲解sqlserver备份还原数据库的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:sqlserver,备份还原数据库,下面大家一起来学习吧。


复制代码 代码如下:

using System;
using SQLDMO;

namespace EDTBackupTool
{
 /// <summary>
 /// Backup 的摘要说明。
 /// </summary>
 public class SQLTools
 { 
  public static bool Backup(string backfile){
   try
   {
    SQLDMO.Backup backup = new BackupClass();
    SQLDMO.SQLServer server = new SQLServerClass();
    server.LoginSecure = true;     
    server.Connect(ClientCommon.CommonFunctions.DataSource,"sa","");      
    backup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
    backup.Database = ClientCommon.CommonFunctions.Catalog;
    backup.Files =backfile;
    backup.BackupSetName =ClientCommon.CommonFunctions.Catalog;
    backup.BackupSetDescription = "数据库备份";
    backup.Initialize = true;    
    backup.SQLBackup(server);  
    return true;
   }
   catch(Exception ex){
    ClientCommon.ExceptionRecorder.Record(ex);
    return false;
   }
  }

  public static bool RestoreDB(string strFileName)
  {
   SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
   try
   {
    svr.LoginSecure=true;    
    svr.Connect(ClientCommon.CommonFunctions.DataSource,"sa","") ;   
    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() == ClientCommon.CommonFunctions.Catalog)
     {
      iColDbName = i ;
     }
     if (iColPIDNum != -1 && iColDbName != -1)
      break ;
    }
    //杀死使用strDbName数据库的进程
    for(int i=1;i<=qr.Rows;i++)
    {
     int lPID = qr.GetColumnLong(i,iColPIDNum) ;
     string strDBName = qr.GetColumnString(i,iColDbName) ;
     if (strDBName.ToUpper() == ClientCommon.CommonFunctions.Catalog)
     {
      svr.KillProcess(lPID) ;
     }
    }

    SQLDMO.Restore res = new SQLDMO.RestoreClass() ;
    res.Action = 0 ;
    res.Files = strFileName ;

    res.Database = ClientCommon.CommonFunctions.Catalog ;
    res.ReplaceDatabase = true ;
    res.SQLRestore(svr) ;
    return true ;
   }
   catch
   {
    return false;
   }
   finally
   {
    svr.DisConnect() ;
   }
  }
 }
}


加载全部内容

相关教程
猜你喜欢
用户评论