[英]VB.net program dataadapter connection closes after fill, but database still shows connection
After running the following sub (VS debugger), I try to detach the database in SSMS, but it shows the connection open still and won't let me detach. 运行以下子程序(VS调试器)后,我尝试在SSMS中分离数据库,但它显示连接仍处于打开状态,不会让我分离。 If I close program in debugger, the database shows no connections.
如果我在调试器中关闭程序,则数据库显示无连接。 I check the dataadapter's connection in the finally block and is shows closed.
我在finally块中检查了dataadapter的连接,并显示为关闭。 What gives
是什么赋予了
Private Function ClientMasterDBFiles(ByVal MasterClientDBConnection As String, ByVal DBName As String) As DataTable
Dim da As SqlDataAdapter
Dim ds As DataSet
Try
ds = New DataSet
da = New SqlDataAdapter
da.SelectCommand = New SqlCommand
With da.SelectCommand
.CommandType = CommandType.StoredProcedure
.Connection = New SqlConnection(MasterClientDBConnection)
.CommandText = "QT_DataSync_GetDBFileLocations"
.Parameters.Add(New SqlParameter("@DBName", SqlDbType.VarChar, 100))
.Parameters.Item("@DBName").Direction = ParameterDirection.Input
.Parameters.Item("@DBName").Value = DBName
.CommandType = CommandType.StoredProcedure
.CommandTimeout = 10
End With
da.Fill(ds)
If ds.Tables.Count > 0 Then
Return ds.Tables(0)
End If
Catch ex As Exception
m_ErrorLog.HandleException(ex)
Throw
Finally
If Not da Is Nothing Then da.Dispose()
If Not ds Is Nothing Then ds.Dispose()
da = Nothing
ds = Nothing
End Try
End Function
I was wrong all along. 我一直都是错的。
Your problem is that the .Net SqlClient classes pool connections. 您的问题是.Net SqlClient类池连接。
You need to explicitly close the SqlCommand's Connection, like this:
您需要显式关闭SqlCommand的Connection,如下所示:
If Not da Is Nothing Then da.SelectCommand.Connection.Close()
However, you should use a
Using
statement instead, like this:
但是,应改为使用
Using
语句,如下所示:
Dim ds As DataSet Try Using da As SqlDataAdapter, _ da.SelectCommand = New SqlCommand, _ da.Connection = New SqlConnection(MasterClientDBConnection) With da.SelectCommand .CommandType = CommandType.StoredProcedure .CommandText = "QT_DataSync_GetDBFileLocations" .Parameters.Add(New SqlParameter("@DBName", SqlDbType.VarChar, 100)) .Parameters.Item("@DBName").Direction = ParameterDirection.Input .Parameters.Item("@DBName").Value = DBName .CommandType = CommandType.StoredProcedure .CommandTimeout = 10 End With da.Fill(ds) If ds.Tables.Count > 0 Then Return ds.Tables(0) End If End Using Catch ex As Exception m_ErrorLog.HandleException(ex) Throw End Try
Also, you shouldn't dispose the DataSet, since you're returning one of its tables. 另外,您不应该处置DataSet,因为您要返回其表之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.