欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-24 11:03:10
复制代码 代码如下:using system;using sqldmo; namespace edtbackuptool{ ///


复制代码 代码如下:

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() ;
   }
  }
 }
}