如果您在Access資料庫、Access項目中删除資料或對象,可能會産生碎片并導緻磁盤空間使用效率的降低。同時,資料庫檔案的大小并未減小,而是不斷的增大,直至您的硬碟沒有空間。有沒有好的處理方法呢?其實,在Access中可以對資料庫進行壓縮優化以提升Access資料庫和Access項目的性能,這樣的壓縮處理的實質是複制該檔案,并重新組織檔案在磁盤上的存儲方式。但是,在Access項目中進行這樣的壓縮不會影響到資料庫對象(例如表或視圖),因為它們是存儲在Microsoft SQL Server資料庫中而不是在Access項目本身中。同樣,這樣的壓縮也不會影響到Access項目中的自動編号。在Access資料庫中,如果已經從表的末尾删除了記錄,壓縮該資料庫是就會重新設定自動編号值。添加的下一個記錄的自動編号值将會比表中沒有删除的最後記錄的自動編号值大一。
下面介紹如何在VB中用一個CompactJetDatabase過程實作對Access資料庫檔案的壓縮處理,在這個過程中有一個可選參數,就是在壓縮前你是否需要把原有的資料庫檔案備份到臨時目錄(True或False)。我用此辦法使21.6MB的資料庫壓縮到僅僅300KB。
‘這些代碼可放在子產品中,在其他窗體也使用
Public Declare Function GetTempPath Lib "kernel32" Alias _
"GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Public Const MAX_PATH = 260
Public Sub CompactJetDatabase(Location As String, Optional BackupOriginal As Boolean = True)
On Error GoTo CompactErr
Dim strBackupFile As String
Dim strTempFile As String
‘檢查資料庫檔案是否存在
If Len(Dir(Location)) Then
‘如果需要備份就執行備份
If BackupOriginal = True Then
strBackupFile = GetTemporaryPath & "backup.mdb"
If Len(Dir(strBackupFile)) Then Kill strBackupFile
FileCopy Location, strBackupFile
End If
‘建立臨時檔案名
strTempFile = GetTemporaryPath & "temp.mdb"
If Len(Dir(strTempFile)) Then Kill strTempFile
‘通過DBEngine壓縮資料庫檔案
DBEngine.CompactDatabase Location, strTempFile
‘删除原來的資料庫檔案
Kill Location
‘拷貝剛剛壓縮過臨時資料庫檔案至原來位置
FileCopy strTempFile, Location
‘删除臨時檔案
Kill strTempFile
Else
End If
CompactErr:
Exit Sub
End Sub
Public Function GetTemporaryPath()
Dim strFolder As String
Dim lngResult As Long
strFolder = String(MAX_PATH, 0)
lngResult = GetTempPath(MAX_PATH, strFolder)
If lngResult <> 0 Then
GetTemporaryPath = Left(strFolder, InStr(strFolder, Chr(0)) - 1)
Else
GetTemporaryPath = ""
End If
End Function