运行以下子程序(VS调试程序)之后,我尝试在SSMS中分离数据库,但它显示连接仍处于打开状态,不会让我分离。如果我在调试器中关闭程序,数据库显示没有连接。我在finally块中检查dataadapter的连接,并显示已关闭。什么给了
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
答案 0 :(得分:0)
我一直都错了。
您的问题是.Net SqlClient类池连接。
您需要显式关闭SqlCommand的Connection,如下所示:
If Not da Is Nothing Then da.SelectCommand.Connection.Close()
但是,您应该使用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
击> <击> 撞击> 此外,您不应该丢弃DataSet,因为您正在返回其中一个表。