vb.net压缩access文件(.accdb)

vb.net压缩access文件(.accdb)

由于access文件(.accdb)会记录操作,所以即使执行了delete数据的处理,该文件的大小还是会不断增加.

解决思路:将原有的access文件(.accdb)复制给一个临时的access文件(.accdb),删除原有文件,再将临时文件复制回原文件名的文件

解决方法:

1.引入引用:

右键项目,选择“添加引用”,在窗口中选择“COM”标签,其中选择“Microsoft Jet and Replication Objects 2.x Library”,点击确定

注:上面的“2.x”中的“x”,是该Library的版本号。

点击“确定”之后,会将Microsoft ActiveX Data Objects Library (ADODB) 和 JRO 这两个DLL添加进项目。

 

2.vb.net程序

'压缩access按钮处理
    Private Sub btnClearAccess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearAccess.Click
        '关闭access链接
        closeAccessConnection()

        Dim jro As JRO.JetEngine

        jro = New JRO.JetEngine()

        accessPath = txtAccess.Text.Trim

        Try
            If accessPath <> "" Then
                jro.CompactDatabase("Provider=microsoft.ACE.OLEDB.12.0;Mode=share Exclusive;Data Source=" & accessPath, _
                "Provider=microsoft.ACE.OLEDB.12.0;Mode=share Exclusive;Data Source=" & accessPath.Replace(".accdb", "1.accdb") & ";Jet OLEDB:Engine Type=5")

                '删除Access文件
                Kill(accessPath)
                jro.CompactDatabase("Provider=microsoft.ACE.OLEDB.12.0;Mode=share Exclusive;Data Source=" & accessPath.Replace(".accdb", "1.accdb"), _
                                    "Provider=microsoft.ACE.OLEDB.12.0;Mode=share Exclusive;Data Source=" & accessPath & ";Jet OLEDB:Engine Type=5")
                Kill(accessPath.Replace(".accdb", "1.accdb"))

                '清空内容
                txtResult.Clear()
                '刷新显示
                txtResult.Refresh()
                txtResult.AppendText(Format(Now(), "H:mm:ss") & Constant.SPACE_2 & "压缩成功!!" & Chr(13) & Chr(10))
                txtResult.Show()
            Else
                MsgBox("请选择相应的 Access 数据库文件!!")
            End If
        Catch ex As Exception
            MsgBox("选择的 Access 数据库文件无法正常打开,请确认该文件是否存在!!")
        End Try
       

    End Sub

 

 '关闭access数据库链接
    Private Sub closeAccessConnection()

        Dim dbConnectionString As String = "Provider=microsoft.ACE.OLEDB.12.0;Mode=share Exclusive;Data Source=" & accessPath

        Dim dbConnection As OleDbConnection = New OleDbConnection(dbConnectionString)

        Try
            If dbConnection.State <> ConnectionState.Closed Then
                dbConnection.Close()
            End If

            If accessConn.State <> ConnectionState.Closed Then
                accessConn.Close()
            End If

        Catch Ex As Exception
            MsgBox("关闭 access 数据库链接出错!!")
        End Try

    End Sub

你可能感兴趣的:(数据库,exception,Microsoft,Access,library,VB.NET)