如何处理本地 SqlConnection?

How do you dispose a local SqlConnection?

我正在编程 vb.net

我想从 mssql 数据库中读取数据。我想让它灵活地处理几个不同的查询,所以我把连接部分放在一个单独的 class 中。每当我想进行查询时,我都可以获得一个预配置的 DataAdapter。 但是由于这种分离,我不知道如何在收集数据后正确处理我的 SqlConnection。

示例性使用:

Public Class Form1
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim DBA As New DBAccess("dummycommand")
        DBA.provideAdapter.Fill(dummytable)
        ...Dispose? 'This is the part where you usually dispose your datacollecting ressources
    End Sub
End Class

Friend Class DBAccess
    Private SqlString As String

    Friend Sub New(ByVal sql As String)
        SqlString = sql
    End Sub

    Friend Function provideAdapter() As SqlDataAdapter
        Dim cn As New SqlConnection("dummyconstring")
        Dim da As New SqlDataAdapter(SqlString, cn)
        Return da
    End Function
End Class

你能告诉我如何改变这个概念以适应处置吗?

您可以让您的数据访问 class 一次性

Friend Class DBAccess
    Implements IDisposable

    Private ReadOnly sqlString As String
    Private disposedValue As Boolean
    Private cn As SqlConnection
    Private da As SqlDataAdapter

    Friend Sub New(sql As String)
        sqlString = sql
    End Sub

    Friend Function provideAdapter() As SqlDataAdapter
        cn = If(cn, New SqlConnection("dummyconstring"))
        da = If(da, New SqlDataAdapter(SqlString, cn))
        Return da
    End Function

    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not disposedValue Then
            If disposing Then
                da?.Dispose()
                cn?.Dispose()
            End If
            disposedValue = True
        End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(disposing:=True)
        GC.SuppressFinalize(Me)
    End Sub

End Class

并像这样使用它

Using DBA As New DBAccess("dummycommand")
    DBA.provideAdapter.Fill(dummytable)
End Using ' Will automatically call Dispose here

但在较长的 运行 中,您可以查看诸如 Entity Framework 之类的 ORM,以使您的生活更轻松。