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 example:
void DoSqlStuff() { SqlConnection sqlConn = new SqlConnection(...); SqlCommand cmd = new SqlCommand(...); SqlDataReader sqlData= null; sqlConn,Open(); sqlData = cmd.ExecutReader(); while(sqlData.Read()) { ... } }
Is it optional, recommended or mandatory to close SqlConn and SqlData?
Thanks.
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: