Imports JRO 'File Interop.JRO.dll
Imports ADODB 'File Interop.ADODB.dll
Public Class frmDBUtil
Private Declare Function apiCopyFile Lib "kernel32" Alias "CopyFileA" (ByVal lpExistingFileName As String, _
ByVal lpNewFileName As String, _
ByVal bFailIfExists As Integer) As Integer
Private Sub btnCompactDB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompactDB.Click
If CompactDB("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= D:\xDB.MDB;Jet OLEDB:Database Password=DB123;", "pwd123") Then
'Success
Else
'Fail
End If
End Sub
Private Function CompactDB(ByVal ConnStr As String, ByVal DbPassword As String) As Boolean
Dim Suc As Boolean = False
Try
Dim dbSource, JetOLEDBPassword As String
Using cn As New System.Data.OleDb.OleDbConnection(ConnStr)
dbSource = cn.DataSource.ToString()
End Using
JetOLEDBPassword = DbPassword
Dim dbName1 As String = dbSource.Substring(dbSource.LastIndexOf("\") + 1)
Dim dbName2 As String = "Backup_" & dbName1
Dim dbPath As String = dbSource.Substring(0, dbSource.LastIndexOf("\")) & "\"
Dim fd As New System.IO.FileInfo(dbPath & dbName2)
If fd.Exists Then
fd.Delete()
End If
Dim jro As New JRO.JetEngine()
jro.CompactDatabase("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbSource & ";Jet OLEDB:Database Password=" & _
JetOLEDBPassword & ";", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & dbName2 & _
";Jet OLEDB:Database Password=" & JetOLEDBPassword & ";" & "Jet OLEDB:Engine Type=5")
Dim iRet As Integer = apiCopyFile(dbPath & dbName2, dbSource, 0)
If iRet = 1 Then
Suc = True
End If
Catch ex As Exception
' MsgBox("Errror")
End Try
Return Suc
End Function
End Class