在VB中壓縮ACCESS數據庫
2024-07-21 02:12:24
供稿:網友
如果您在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
以后您在使用access數據庫時可以嘗試進行這樣的壓縮,您應該會發現我說的沒有錯。