难道SqlDataAdapter.Dispose实际上关闭了相关的SqlConnection?关闭了、SqlDataAdapter、Dispose、SqlConnection

2023-09-03 12:52:45 作者: つ゜ 她那么想她。  

有谁知道,如果SqlDataAdapter.Dispose方法实际上将关闭或处置任何SqlConnections?我装了反光镜和我看到的SqlDataAdapter自DbDataAdapter继承。如果我拆开看看在类Dispose方法,但似乎没有处理任何SqlConnections。我想我可以写一个测试这一点,但我想我会问问看是否有人对这个任何见解。

Does anyone know if the SqlDataAdapter.Dispose method actually closes or disposes any SqlConnections? I loaded up Reflector and I see that SqlDataAdapter inherits from DbDataAdapter. If I disassemble and look at the dispose method in that class, there appears to be no disposal of any SqlConnections. I suppose I could write a test for this, but I figured I would ask to see if anyone had any insight on this.

推荐答案

要了解的第一件事是,DataAdapter的不管理,并关闭在某些情况下,您的连接。例如,如果你正在使用DataAdapter你可能在操作使用.fill伪()和.Update数据表/数据集()函数。

The first thing to be aware of is that the DataAdapter does manage and close your connection in some circumstances. For example, if you're using a DataAdapter you're probably operating on DataTables/DataSets using the .Fill() and .Update() functions.

从 .fill伪()文档:

与SELECT语句相关联的连接对象必须是有效的,但它并不需要开放。如果填充被称为前连接关闭,其打开以检索数据,然后关闭。如果连接是打开填充被调用之前,它仍然是开放的。

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

借助 .Update()文档没有提及有关连接任何东西,所以我期望需要手动管理它。

The .Update() docs don't mention anything about the connection at all, so I would expect to need to manage it manually.

现在您专门询问了Dispose()方法。像更新,在的Dispose()文档没有具体提到的连接,所以我期望需要手动关闭它。

Now you asked specifically about the Dispose() method. Like Update, the Dispose() docs don't specifically mention the connection, so I would expect to need to close it manually.

最后,我们可以提高鲍勃金的code稍微像这样的:

Finally, we can improve on Bob King's code slightly like this:

Using conn as New SqlConnection(""), _
      adapter as New SqlDataAdapter() With {.Connection = conn}
    'Do stuff
End Using

或者在C#:

Or in C#:

using (SqlConnection conn = new SqlConnection(""))
using (SqlDataAdapter adapter = new SqlDataAdapter() {Connection = conn})
{
    // Do stuff
}

不是100%我适配器正确初始化的语法,但我直接输进了答复窗口。我将来有需要修复它。

Not 100% I got the initialize syntax for the adapter right, but I typed it directly into the reply window. I'll fix it later if needed.