如何用程序实现异地备份数据库?

解决方案 »

  1.   

    用sql语句backup 'RESTORE 等,也可以用sql server中的存储过程
    下面的例子是我贴来的,不知道能不能用,不过大概可以起个引导作用。procedure TBak.btnRestoreClick(Sender: TObject);
    var
      Qry:TADOQuery;
    begin
      if FileExists(self.edtReStorePath.Text) then
        begin
          DM.Conn.Connected:=False; //断开系统数据库连接
          Qry:=TADOQuery.Create(self);
          Qry.CommandTimeout:=120;
          //把连接转移到master库
          Qry.ConnectionString:='Provider=SQLOLEDB.1;Password='+Login.GetDBServerInfo('Pwd')+';Persist Security Info=True;User ID='+Login.GetDBServerInfo('User')+';Initial Catalog=master;Data Source='+Login.GetDBServerInfo('Server');
          //-------------------端开rxd_CRM库------------------------------------------
          Qry.Close;
          Qry.SQL.Clear;
          Qry.SQL.Text:='ALTER DATABASE rxd_CRM SET OFFLINE WITH ROLLBACK IMMEDIATE';
          Qry.Prepared;
          Qry.ExecSQL;
          //------------------- 端开rxd_CRM库结束-------------------------------------
          Qry.Close;
          Qry.SQL.Clear;
          Qry.SQL.Text:='RESTORE DATABASE rxd_CRM FROM DISK='''+self.edtReStorePath.Text+''' with replace';
          Qry.Prepared;
          try
            Qry.ExecSQL;
            Login.MsgInfo('成功恢复数据!');
          finally
            //-------------------重新连接rxd_CRM库------------------------------------
            Qry.Close;
            Qry.SQL.Clear;
            Qry.SQL.Text:='ALTER DATABASE rxd_CRM SET ONLINE WITH ROLLBACK IMMEDIATE';
            Qry.Prepared;
            Qry.ExecSQL;
            //-------------------重新连接rxd_CRM库结束--------------------------------
            Qry.Free;
            DM.Conn.ConnectionString:=Login.GetDBServerInfo('DBStr');
            try
              DM.Conn.Connected:=True;
            except
              Login.MsgError('连接数据库失败,请尝试重启系统!');
            end;
          end
        end
      else
        begin
          Login.MsgInfo('数据文件不存在,请重新选择!');
          self.edtReStorePath.SetFocus;
        end;
    end;
      

  2.   

    至于异地,根据ip地址连接sql server就可以了。
    下面这段代码应该可以用备份:
    procedure TBackupFrm.BitBtn2Click(Sender: TObject);
    begin
      if Edit1.Text= '' then
        begin
          Showmessage('无选择要保存的文件名');
          exit;
        end;
      try
        try
          dmData.adoQryTmp.Active:= false;
          dmData.adoQryTmp.SQL.Clear;
          dmData.adoQryTmp.SQL.Add('BACKUP DATABASE [dzyl] TO DISK = '''+edit1.text+''' WITH INIT');
          dmData.adoQryTmp.ExecSQL;
        finally
          begin
            dmData.adoQryTmp.Active:= false;
            Showmessage('数据库备份成功!');
          end;
        end;
      except
      on e:exception do
        begin
          ShowMessage('数据库备份失败!');
        end;
      end;
    end;
    ---------------
    恢复
    procedure TBackupFrm.BitBtn4Click(Sender: TObject);
    begin
      if Edit2.Text = '' then
        begin
          showmessage('未选择要恢复的数据库文件!');
          exit;
        end;
      with dmData do
      begin
        try
          adocmmd.CommandText:='use master';
          adocmmd.Execute;
          adocmmd.CommandText:=' alter database dzyl set offline with rollback immediate';
          adocmmd.Execute;
          adocmmd.CommandText:='restore database dzyl from disk= '''+edit2.Text+''' with recovery ';
          adocmmd.Execute;
          adocmmd.CommandText:=' alter database dzyl set online with rollback immediate';
          adocmmd.Execute;
          showmessage('数据库恢复成功!');
          application.Terminate;
        except
        on e:exception do
          begin
            showmessage('数据库恢复失败!'+e.Message);
          end;    end;
      end;
      end;
      

  3.   

    备份数据库代码:
    procedure TDataBaseBackandRestoreFrm.cxButton1Click(Sender: TObject);
    var
      DataPath: string;
      state:boolean;
    begin
      state:=FramedataCommonDM.ProFrameadoCN.Connected;
      if state then
      FramedataCommonDM.ProFrameadoCN.Connected:=false;
      try
        self.Caption := '正在备份数据....';
        SaveDialog1.Filter := '备份文件 (*.back)|*.back|所有文件 (*.*)|*.*';
        SaveDialog1.InitialDir := ExtractFileDir(Application.ExeName) + '\backupdata';
        if SaveDialog1.Execute then
          begin
            DataPath:= SaveDialog1.FileName;
            DataPath:=DataPath+'.back';
          end;      
        screen.Cursor:=crSQLWait;
        self.Refresh;
        if DataPath <> '' then
        begin
          BackRestoreConnection.ConnectionString:='Provider=SQLOLEDB.1;Password=1;Persist Security Info=True;User ID=sa;Initial Catalog=CorpManagedb';
          adocommand1.CommandText:= 'backup database CorpManagedb to disk=''' + DataPath + '''';// + '.bak'; //cback:TADOCommand //cback.connection:=Backconn
          BackRestoreConnection.Connected := true;
          try
            try
              adocommand1.Execute;
              application.MessageBox('备份成功!', '提示', MB_OK);//MB_ICONSTOP
            except
              application.MessageBox('数据库正在被使用!请确定已关闭其它使用该数据库程序!备份失败!', '提示', MB_ICONSTOP);//
            end;
          finally
            try
              BackRestoreConnection.Connected := false;
            except
              application.MessageBox('程序运行发生不可预知错误,请重新启动程序!', '提示', MB_ICONSTOP);//
              Application.Terminate;
            end;
          end;
        end;
        self.Caption := '数据备份和恢复';
      finally
        screen.Cursor:=crDefault;
      end;
      FramedataCommonDM.ProFrameadoCN.Connected:=state;
    end;
    回复数据库代码:procedure TDataBaseBackandRestoreFrm.cxButton2Click(Sender: TObject);
    var
      DataPath: string;
      state:boolean;
      s:string;
    begin
      state:=FramedataCommonDM.ProFrameadoCN.Connected;
      if state then
      FramedataCommonDM.ProFrameadoCN.Connected:=false;  if FramedataCommonDM.CheckPassword=false then
      begin
        Application.MessageBox('密码错误!','提示',MB_OK+MB_ICONSTOP);
        exit;
      end;
      if Application.MessageBox(PChar('特别提示:即将恢复数据库,所有数据将丢失,并不可恢复!!!确实要初始化吗?'),'警告询问',MB_ICONQUESTION + MB_YESNO + MB_DEFBUTTON2) = IDNO then exit;  if Application.MessageBox(PChar('警告:恢复后数据不可恢复!确实要恢复数据库吗?'),'再次确认',MB_ICONQUESTION + MB_YESNO + MB_DEFBUTTON2) = IDNO then exit;  if Application.MessageBox(PChar('再次警告:恢复后数据不可恢复!确实要恢复数据库吗?'),'再次确认',MB_ICONQUESTION + MB_YESNO + MB_DEFBUTTON2) = IDNO then exit;  if Application.MessageBox(PChar('最后警告:恢复后数据不可恢复!确实要恢复数据库吗?'),'再次确认',MB_ICONQUESTION + MB_YESNO + MB_DEFBUTTON2) = IDNO then exit;  try
        self.Caption := '正在恢复数据....';
        OpenDialog1.Filter := '备份文件 (*.back)|*.back|所有文件 (*.*)|*.*';
        OpenDialog1.InitialDir := ExtractFileDir(Application.ExeName) + '\backupdata';
        if OpenDialog1.Execute then
          DataPath:= OpenDialog1.FileName;
        screen.Cursor:=crSqlWait;
        self.Refresh;
        if DataPath <> '' then
        begin
          BackRestoreConnection.ConnectionString:='Provider=SQLOLEDB.1;Password=1;Persist Security Info=True;User ID=sa;Initial Catalog=master';
          BackRestoreConnection.Connected := true;
          if application.MessageBox('此操作将使上次备份以来的所有数据丢失,是否继续?', '恢复数据', MB_OKCANCEL) = idOK then
          begin
            s:='Use master ';
            s:=S+' ALTER DATABASE CorpManagedb SET OFFLINE WITH ROLLBACK IMMEDIATE ';
            //adocommand1.CommandText:= 'restore database CorpManagedb from disk=''' + DataPath + '''';// + '.bak'; //cback:TADOCommand //cback.connection:=Backconn
            s:=s+'restore database CorpManagedb from disk=''' + DataPath + '''';// + '.bak'; //cback:TADOCommand //cback.connection:=Backconn
            adocommand1.CommandText:=s;
            try
              try
                adocommand1.Execute;
                //cmdsql(adoquery1,s,false);
                application.MessageBox('恢复成功!', '提示', MB_OK);//MB_ICONSTOP
              except
                 application.MessageBox('数据库正在被使用!请确定已关闭其它使用该数据库程序!恢复失败!', '提示', MB_ICONSTOP);
              end;
            finally
              try
                BackRestoreConnection.Connected := false;
              except
                application.MessageBox('程序运行发生不可预知错误,请重新启动程序!', '提示', MB_ICONSTOP);//
                Application.Terminate;
              end;
            end;
          end;
        end;
        self.Caption := '数据备份和恢复';
      finally
        screen.Cursor:=crDefault;
      end;
      FramedataCommonDM.ProFrameadoCN.Connected:=state;
    end;