SqlCommand (Using Statement / Disposing issue)

帅比萌擦擦* 提交于 2019-12-04 02:34:51

The DataAdapter.Fill command will open and close the connection itself, so you don't need the cmd.Connection.Open(). (Ref: the remarks section in http://msdn.microsoft.com/en-us/library/377a8x4t.aspx .)

Using Using for the SqlConnection has the effect of calling .Close on it for you.

The variable cmd becomes eligible for garbage collection once it is out of scope (or earlier if .NET determines it isn't going to be used again).

In your example 2, I'm not sure it's such a good idea to dispose of the cmd before the DataAdapter has used it.


[Information from user "JefBar Software Services" in Should I call Dispose on a SQLCommand object? ] At the time of writing, calling .Dispose on an SqlCommand has no effect because of the code in its constructor:

public SqlCommand() : base() {
    GC.SuppressFinalize(this);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!