C# - closing Sql objects best practice

前端 未结 8 1052
陌清茗
陌清茗 2020-12-31 11:29

If you have a C# function with Sqlaccess, is it mandatory to close all objects/handles, or is everything cleaned up automatically once you exit the function

For exam

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 11:58

    You should close the SqlConnection object as soon as you're done with it. If you don't then the connection will remain open, and will not be available to handle other requests.

    The using statement is useful for this. It will call Dispose() on the object for you:

    using (SqlConnection cn = new SqlConnection(connectionString))
    {   
        SqlCommand cm = new SqlCommand(commandString, cn)
        cn.Open();
        cm.ExecuteNonQuery();       
    }
    

提交回复
热议问题