0

我在 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

并且每次在数据库操作中调用这个方法。但它仍然向我展示了太多的活动连接。

4

1 回答 1

0

如果使用 using 语句连接到数据库,则不需要使用 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

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

更多信息:

如何关闭asp.net中的sqlconnection

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

于 2013-02-22T13:11:06.633 回答