.NET和关闭SQL Server连接

时间:2010-04-27 02:44:54

标签: asp.net sql-server-2005

我很难弄清楚为什么以下构造函数不会关闭连接。当我查看活动连接时。这是我的代码。

Public Sub New(ByVal UserID As Integer)

Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString())
Dim cmd As New SqlCommand("stored proc", oConn)
Dim sdr As SqlDataReader

cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@userID", UserID)
oConn.Open()
sdr = cmd.ExecuteReader()

Try
    If Not sdr.HasRows Then
        sdr.Close()

        If Not oConn Is Nothing Then
            If oConn.State <> ConnectionState.Closed Then
                oConn.Close()
            End If
        End If
        cmd.Dispose()

        Exit Sub
    End If
    'User has account in WATS, proceed to load account information
    While sdr.Read
         _firstname = Convert.ToString(sdr("First Name"))
        _lastname = Convert.ToString(sdr("Last Name"))
    End While

Catch ex As Exception
    'Throw New Exception("User Error: " + ex.Message)
Finally
    sdr.Close()

    If Not oConn Is Nothing Then
        If oConn.State <> ConnectionState.Closed Then
            oConn.Close()
        End If
    End If
    cmd.Dispose()
End Try

End Sub

3 个答案:

答案 0 :(得分:2)

由于连接池可能会打开。

ADO.NET Connection Pooling & SQLServer

答案 1 :(得分:2)

您需要实施Using块。部分修复:

Using oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString()) 
    Using cmd As New SqlCommand("stored proc", oConn) 

        cmd.CommandType = CommandType.StoredProcedure 
        cmd.Parameters.AddWithValue("@userID", UserID) 
        oConn.Open() 
        Using sdr As SqlDataReader = cmd.ExecuteReader() 
        End Using
    End Using
End Using

答案 2 :(得分:1)

Dim oConn As SqlConnection
Dim cmd As SqlCommand
Dim sdr As SqlDataReader

Try
    oConn = New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString())
    cmd = New SqlCommand("stored proc", oConn)

    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters.AddWithValue("@userID", UserID)
    oConn.Open()
    sdr = cmd.ExecuteReader()
Catch ex As Exception

Finally

    If Not IsNothing(sdr) Then
        If Not sdr.IsClosed Then sdr.Close()
    End If

    If Not IsNothing(oConn) Then
        If oConn.State = ConnectionState.Open Then oConn.Close()
    End If

End Try