在VB中壓縮ACCESS數(shù)據(jù)庫
2024-09-07 19:05:02
供稿:網(wǎng)友
如果您在access數(shù)據(jù)庫、Access項目中刪除數(shù)據(jù)或對象,可能會產(chǎn)生碎片并導致磁盤空間使用效率的降低。同時,數(shù)據(jù)庫文件的大小并未減小,而是不斷的增大,直至您的硬盤沒有空間。有沒有好的處理方法呢?其實,在Access中可以對數(shù)據(jù)庫進行壓縮優(yōu)化以提升Access數(shù)據(jù)庫和Access項目的性能,這樣的壓縮處理的實質(zhì)是復制該文件,并重新組織文件在磁盤上的存儲方式。但是,在Access項目中進行這樣的壓縮不會影響到數(shù)據(jù)庫對象(例如表或視圖),因為它們是存儲在Microsoft SQL Server數(shù)據(jù)庫中而不是在Access項目本身中。同樣,這樣的壓縮也不會影響到Access項目中的自動編號。在Access數(shù)據(jù)庫中,如果已經(jīng)從表的末尾刪除了記錄,壓縮該數(shù)據(jù)庫是就會重新設置自動編號值。添加的下一個記錄的自動編號值將會比表中沒有刪除的最后記錄的自動編號值大一。
下面介紹如何在VB中用一個CompactJetDatabase過程實現(xiàn)對Access數(shù)據(jù)庫文件的壓縮處理,在這個過程中有一個可選參數(shù),就是在壓縮前你是否需要把原有的數(shù)據(jù)庫文件備份到臨時目錄(True或False)。我用此辦法使21.6MB的數(shù)據(jù)庫壓縮到僅僅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
‘檢查數(shù)據(jù)庫文件是否存在
If Len(Dir(Location)) Then
‘如果需要備份就執(zhí)行備份
If BackupOriginal = True Then
strBackupFile = GetTemporaryPath & "backup.mdb"
If Len(Dir(strBackupFile)) Then Kill strBackupFile
FileCopy Location, strBackupFile
End If
‘創(chuàng)建臨時文件名
strTempFile = GetTemporaryPath & "temp.mdb"
If Len(Dir(strTempFile)) Then Kill strTempFile
‘通過DBEngine壓縮數(shù)據(jù)庫文件
DBEngine.CompactDatabase Location, strTempFile
‘刪除原來的數(shù)據(jù)庫文件
Kill Location
‘拷貝剛剛壓縮過臨時數(shù)據(jù)庫文件至原來位置
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
以后您在使用Access數(shù)據(jù)庫時可以嘗試進行這樣的壓縮,您應該會發(fā)現(xiàn)我說的沒有錯。