Closing SqlConnection and SqlCommand c#

后端 未结 3 423
感动是毒
感动是毒 2021-01-01 21:26

In my DAL I write queries like this:

using(SQLConnection conn = \"connection string here\")
{
    SQLCommand cmd = new (\"sql query\", conn);
    // execute          


        
相关标签:
3条回答
  • 2021-01-01 21:29

    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
        }
    }
    
    0 讨论(0)
  • 2021-01-01 21:33

    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.

    0 讨论(0)
  • 2021-01-01 21:51

    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
    }
    
    0 讨论(0)
提交回复
热议问题