delphi操作sql数据库的备份和强制还原

procedure TFrmMain.NSystBackupClick(Sender: TObject);
var strFile:string;
begin
  //  数据库备份
  SaveDlgData.Filter:='All files (*.*)|*.*';
  SaveDlgData.FileName:='DataBack'+DateToStr(now);
  if SaveDlgData.Execute then
  begin
    strFile:=SaveDlgData.FileName;
    StatusBar1.Panels[1].Text:='正在备份数据库...';
    DataModuleMain.ADOQBack.Close;
    DataModuleMain.ADOQBack.SQL.Clear;
    DataModuleMain.ADOQBack.SQL.Add('backup database DangerWaste to disk='''+strFile+''' ');
   
    try
      DataModuleMain.ADOQBack.ExecSQL;
      Application.MessageBox(pchar('数据库已经备份到'+strFile+'!'),'提示',MB_OK+MB_ICONINFORMATION );
      //write log
      DataModuleMain.AddLog(currentUser.Name,'备份数据库到'+strFile,DateTimeTostr(now));
      StatusBar1.Panels[1].Text:='';
    except
      Application.MessageBox('文件写入错误!','错误',MB_OK+MB_ICONERROR );
    end;
  end;
end;
procedure TFrmMain.NSysRestoreClick(Sender: TObject);
//数据库还原
var strFile:string;
begin
  if OpenDlgRestore.Execute then
  begin
   
    strFile:=OpenDlgRestore.FileName;
    if messagedlg('是否确定还原',mtconfirmation,[mbyes,mbno],0)=mryes then
    begin
      StatusBar1.Panels[1].Text:='正在恢复数据库...';
      try
        with DataModuleMain do
        begin
          ADOConnMain.Close;
          ADOConnectRestore.Open();//主义这个connection连接的是master数据库
          ADOQRestore.Close;
          ADOQRestore.SQL.Clear;
          ADOQRestore.SQL.Add('ALTER DATABASE DangerWaste SET OFFLINE WITH ROLLBACK IMMEDIATE');
          ADOQRestore.ExecSQL;
          ADOQRestore.Close;
          ADOQRestore.SQL.Clear;
          ADOQRestore.SQL.Add('restore database DangerWaste From disk='''+strFile+''' ');
          ADOQRestore.ExecSQL;
          ADOConnectRestore.Close;
          ADOConnMain.Connected:=true;
        end;
        Application.MessageBox(pchar('数据库恢复成功!'),'提示',MB_OK+MB_ICONINFORMATION );
        DataModuleMain.AddLog(currentUser.Name,'还原数据库从'+strFile,DateTimeTostr(now));
        StatusBar1.Panels[1].Text:='';
      except
        Application.MessageBox('数据库联接错误','错误',MB_OK+MB_ICONERROR);
      end;
    end;
  end;
end;
posted @ 2009-12-18 04:06  bingege  阅读(1168)  评论(0编辑  收藏  举报