1

我有一个类来打开一个 sqlconnection 并通过主应用程序引用该连接返回,问题是这个连接总是没有如何修改这个行为:

班级代码:

Public Class Class1
Public ClassConnection As SqlClient.SqlConnection

Public Function OpenConnection() As Object
    Try
        Dim sConnString As String = ""
        sConnString = "Server=ServerName;Database=DBName;User ID=Username;Password=MyPassword"
        Using ClassConnection As New SqlClient.SqlConnection
            ClassConnection.ConnectionString = sConnString
            ClassConnection.Open()
            Return ClassConnection
        End Using
    Catch ex As Exception
        Throw ex
        Return Nothing
    End Try
End Function

结束类

我的表格代码:

Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim uu As New Class1
    Dim iii As SqlClient.SqlConnection = uu.OpenConnection()
    MsgBox(iii.State)
End Sub

结束类

4

1 回答 1

1

您的问题是,通过将其包装在一个Using块中,您将在ClassConnection返回它时立即处理它。

Using ClassConnection As New SqlClient.SqlConnection
    ClassConnection.ConnectionString = sConnString
    ClassConnection.Open()
    Return ClassConnection
End Using ' This is equivalent to calling ClassConnection.Dispose()

应该只是:

Dim ClassConnection As New SqlClient.SqlConnection
ClassConnection.ConnectionString = sConnString
ClassConnection.Open()
Return ClassConnection

然后由客户端负责处理连接。

注意:让客户端负责清理通常被认为是糟糕的 API 设计。我建议调查工作单元模式

于 2013-03-21T16:15:51.563 回答