如何关闭活动的SQL Server连接?

时间:2013-02-22 12:52:53

标签: asp.net sql-server-2008

我在dispose()方法中使用以下代码

 Public Sub Dispose() Implements System.IDisposable.Dispose
            If Not IsDBNull(Command) And Not Command Is Nothing Then
                Dim tmpsqlcon As SqlConnection
                tmpsqlcon = Command.Connection
                Debug.Assert(Not IsDBNull(tmpsqlcon))
                SqlConnection.ClearPool(tmpsqlcon)
                tmpsqlcon.Close()
                Command.Dispose()
                tmpsqlcon.Dispose()
            End If
        End Sub

每次在数据库操作中调用此方法。但它仍然显示我有太多活跃的连接。

1 个答案:

答案 0 :(得分:0)

如果使用using语句连接到db,则不需要使用dispose:

示例:

Dim queryString As String = _
    "SELECT OrderID, CustomerID FROM dbo.Orders;" 

Using connection As New SqlConnection(connectionString)
    Dim command As New SqlCommand(queryString, connection)
    connection.Open()

    Dim reader As SqlDataReader = command.ExecuteReader()

    ' Call Read before accessing data. 
    While reader.Read()
        Console.WriteLine(String.Format("{0}, {1}", _
            reader(0), reader(1)))
    End While 

    ' Call Close when done reading.
    reader.Close()
End Using

这是您应该连接到数据库的方式。

更多信息:

how to close a sqlconnection in asp.net

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.close.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2