2013-02-12 19 views
0

我連接到Access數據庫,我想知道如果重寫子敲定在我cconnectionDB.vb將是有益的:覆蓋子敲定做出數據庫確保連接關閉

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 

回答

1

這不是非常有用。直到垃圾收集器摧毀對象時纔會調用解構器Finalize。而且,由於DbConn對象將是唯一引用DbConnection對象的對象,所以它會自動同時銷燬它。如果您想在完成連接後立即釋放連接,則建議的方法是在班級中實現IDisposable接口。例如:

Private Class DbConn 
    Implements IDisposable 

    Private DataCon As DbConnection 
    Private disposedValue As Boolean 

    Protected Overridable Sub Dispose(disposing As Boolean) 
     If Not Me.disposedValue Then 
      If disposing Then 
       Try 
        DataCon.Close() 
       Catch ex As Exception 
       End Try 
      End If 
     End If 
     disposedValue = True 
    End Sub 

    Public Sub Dispose() Implements IDisposable.Dispose 
     Dispose(True) 
     GC.SuppressFinalize(Me) 
    End Sub 
End Class 

但是,如果實現IDisposable,你的工作是不是有做。 IDisposable對象上的Dispose方法不會自動調用。您需要通過手動調用Dispose方法來告訴對象。另外,您也可以使用Using塊:

Using d As New DbConn 
    ' The DbConn.Dispose method automatically gets called once execution leaves this Using block 
End Using 
+0

但我仍然需要重寫'finlize'還是應該放在哪裏呢? – cMinor 2013-02-12 16:55:47

+0

不,在這種情況下,沒有理由重寫'Finalize'。 – 2013-02-12 16:57:27