通用的自动备份数据库函数(原创)

在 DataModule 的 OnDestroy 事件中调用以下函数即可。

procedure TDataModule1.DoBackup;
const
  // 主数据库
  DB_FILE_NAME = 'Orders.db';
  KeepBackupNums = 5;
  PRE = 'db';
  SUFFIX = '.bak';
var
  SR: TSearchRec;
  FileList: TStringList;
  IsFound: Boolean;
  strDir, strNewBackupFile: string;
begin
  strDir := ExtractFilePath(ParamStr(0));
  if strDir[length(strDir)] <> '\' then strDir := strDir + '\';

  // 如果指定时刻的备份不存在则创建指定备份(备份时刻精确到分)
  strNewBackupFile := strDir + PRE + FormatDatetime('yyyymmddhhnn', Now) + SUFFIX;
  if not FileExists(strNewBackupFile) then
    CopyFile(Pchar(strDir + DB_FILE_NAME), Pchar(strNewBackupFile), True); // 不覆盖同名文件

  FileList := TStringList.Create;

  IsFound := FindFirst(strDir + PRE + '*' + SUFFIX, faAnyFile-faDirectory, SR) = 0;
  while IsFound do
  begin
   FileList.Add(strDir + SR.Name);
   IsFound := FindNext(SR) = 0;
  end;
  // 不加上 SysUtils,会优先引用windows.pas中的同名函数而提示参数类型错误
  SysUtils.FindClose(SR);

  // 按日期排序,并按保留数目删除过早的备份文件
  FileList.Sort;
  while FileList.Count > KeepBackupNums do begin
    SysUtils.DeleteFile(FileList[0]);    // 优先调用 SysUtils中的同名函数
    FileList.Delete(0);                  // 同步删除文件列表中的项目,否则无法退出循环
  end;
  FileList.Free;
end;
posted @ 2024-08-23 08:57  汉学  阅读(11)  评论(0)    收藏  举报