CompactDB.pas 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. { 压缩数据库 }
  2. unit CompactDB;
  3. interface
  4. uses ComObj, Windows, SysUtils, Classes, ZhAPI, Variants, UtilMethods;
  5. function CompactDatabase(AFileName: string): Boolean;
  6. implementation
  7. // 获得临时文件名
  8. function GetTempFileName(AExt: string): string;
  9. var
  10. Ext: string;
  11. begin
  12. if AExt = '' then
  13. Ext := '.tmp'
  14. else
  15. Ext := AExt;
  16. Result := GetTempFilePath + GetRandomString(6) + Ext;
  17. while FileExists(Result) do
  18. begin
  19. Result := GetTempFilePath + GetRandomString(6) + Ext;
  20. end;
  21. end;
  22. var
  23. FileList: TStringList = nil;
  24. function FileListName: string;
  25. begin
  26. Result := GetTempFilePath + 'spbkt.bak';
  27. end;
  28. function GetFileList: TStringList;
  29. begin
  30. if FileList = nil then
  31. begin
  32. FileList := TStringList.Create;
  33. if FileExists(FileListName) then
  34. FileList.LoadFromFile(FileListName);
  35. end;
  36. Result := FileList;
  37. end;
  38. procedure UpdateFileList;
  39. begin
  40. if FileExists(FileListName) then
  41. DeleteFile(FileListName);
  42. GetFileList.SaveToFile(FileListName);
  43. end;
  44. procedure AddToFileList(AFileName: string);
  45. begin
  46. try
  47. GetFileList.Add(AFileName);
  48. UpdateFileList;
  49. except
  50. end;
  51. end;
  52. // 压缩与修复数据库,覆盖源文件
  53. function CompactDatabase(AFileName: string): Boolean;
  54. var
  55. strTempFileName: string;
  56. vJE: OleVariant;
  57. const
  58. // 注意:此处的连接语句没有“;Persist Security Info=True”
  59. SConnectStr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;User ID=%s;Password=%s';
  60. begin
  61. if not FileExists(AFileName) then Exit;
  62. strTempFileName := GetTempFileName('');
  63. try
  64. AddToFileList(strTempFileName);
  65. vJE := CreateOleObject('JRO.JetEngine');
  66. vJE.CompactDatabase(Format(SConnectStr, [AFileName, 'Admin', '']),
  67. Format(SConnectStr, [strTempFileName, 'Admin', '']));
  68. vJE := Unassigned;
  69. Result := CopyFile(PChar(strTempFileName), PChar(AFileName), False);
  70. DeleteFile(strTempFileName);
  71. except
  72. vJE := Unassigned;
  73. Result := False;
  74. end;
  75. end;
  76. initialization
  77. finalization
  78. FileList.Free;
  79. end.