从class或dll文件中调用它时,我的sqlconnection始终没有任何意义

时间:2013-03-21 16:13:24

标签: vb.net

我有一个类打开一个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

结束班

1 个答案:

答案 0 :(得分: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设计。我建议调查Unit-of-Work pattern