sqlserver备份还原数据库封装类

本文介绍了一个针对SQLServer数据库备份与还原功能的封装实现,包括使用SQLDMO进行数据库备份的方法及通过指定备份文件来恢复数据库的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sqlserver备份还原数据库功能封装。
using System;
using SQLDMO;
namespace EDTBackupTool
{
 /// <summary>
 /// Backup 的摘要说明。
 /// </summary>
 public class SQLTools
 { www.jbxue.com
  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() ; 
   } 
  } 
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值