Does connection close when command is disposed and the connection is defined directly on the command?

空扰寡人 提交于 2019-12-01 15:57:53

问题


I know that a lot of examples exist where a SqlConnection is defined and then a SqlCommand is defined, both in Using blocks:

using (var conn = new SqlConnection(connString)) {
      using (var cmd = new SqlCommand()) {
        cmd.Connection = conn;
        //open the connection
      }
}

My question: If I define the connection directly on the SqlCommand, does the connection close when the command is disposed?

using (var cmd = new SqlCommand()) {
      cmd.Connection = new SqlConnection(connString);
      //open the connection
}

回答1:


No, SqlCommand never attempts to close/dispose of the connection.




回答2:


No, the connection object will not be disposed until you dispose it explicitly. But my recommendation is to use using blocks whenever you can.




回答3:


It does not close the connection, you need to either close it yourself or put it in its own using statment.

Also here is a tip to make your using blocks a bit more readable:

using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand())
{
    cmd.Connection = conn;
}



回答4:


@milot

But my recommendation is to use using blocks whenever you can.

Using Using Blocks is nice but useless when working with non IDisposable Objects and so this can be confusing if you use Using Blocks anywhere.

Be careful since your objects might not being Disposed if they don't implements IDisposable.

Hope this helps.



来源:https://stackoverflow.com/questions/410222/does-connection-close-when-command-is-disposed-and-the-connection-is-defined-dir

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