Closing SqlConnection and SqlCommand c#

为君一笑 提交于 2019-11-30 11:33:19

No, the using statement will not take care of the command.

You should wrap the commands with using statements as well, since this will properly call Dispose on them:

using(SQLConnection conn = 'connection string here')
{
    using(SQLCommand cmd = new ('sql query', conn))
    {
        //execute it blah blah
    }
}

The SqlConnection has no knowledge about the SqlCommand, so you should close it by itself:

using (SqlConnection conn = new SqlConnection("connection string here"))
using (SqlCommand cmd = new SqlCommand("sql query", conn))
{
    // execute it blah blah
}

It won't handle the SqlCommand, but the SqlCommand will eventually be handled by the garbage collector. I tend to do the following:

using (SqlConn conn ... )
using (SqlComm comm ... )
{
    conn.Open();
}

Stacking the using statements here will handle both.

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