I am connecting to Access Database and I am wondering if overriding Sub finalize in my cconnectionDB.vb would be useful:
Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.IO
Public Class DbConn
Private DataCon As DbConnection
Private DBConnectionOpen As Boolean = False
Protected Overrides Sub finalize()
Try
DataCon.Close()
Catch ex As Exception
End Try
End Sub
Public Sub OpenDatabaseConnection()
Try
DataCon.Open()
Catch ex As Exception
Throw New System.Exception("Error opening data connection.", ex.InnerException)
DBConnectionOpen = False
Exit Sub
End Try
DBConnectionOpen = True
End Sub
Public Sub CloseDatabaseConnection()
DataCon.Close()
DBConnectionOpen = False
End Sub
''' <summary>
''' Creates a new connection to an Access database
''' </summary>
''' <param name="FileName">The full path of the Access file</param>
''' <remarks></remarks>
Public Sub New(ByVal FileName As String)
'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False;
Dim fileData As FileInfo = My.Computer.FileSystem.GetFileInfo(FileName)
DataCon = New OleDb.OleDbConnection
Dim csb As OleDb.OleDbConnectionStringBuilder = New OleDb.OleDbConnectionStringBuilder
csb.ConnectionString = "Data Source=" & FileName
Select Case fileData.Extension.ToLower
Case ".mdb" : csb.Add("Provider", "Microsoft.Jet.Oledb.4.0")
Case ".accdb" : csb.Add("Provider", "Microsoft.ACE.OLEDB.12.0")
End Select
DataCon.ConnectionString = csb.ConnectionString
Try
DataCon.Open()
DataCon.Close()
Catch ex As Exception
Throw New System.Exception("Unable to connect to database.", ex.InnerException)
End Try
End Sub
End Class
That’s not terribly useful. The
Finalizedeconstructor won’t be called until the garbage collector gets around to destroying the object. And, since theDbConnobject would be the only thing that has a reference to theDbConnectionobject, it would automatically destroy that at the same time anyway. If you want to free the connection as soon as you are done with it, the recommended method is to implement theIDisposableinterface in your class. For instance:However, if you implement
IDisposable, your work isn’t done there. TheDisposemethod onIDisposableobjects never gets called automatically. You need to tell the object when you are done with it by calling the Dispose method manually. Alternatively, you could use aUsingblock: