Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using statement - is this more useful for the sql connection than the sql adapter?

Tags:

c#

sql-server

I know that the following statement is useful for garbage collection. Effectively it must be the same as Try/Catch/finally. If I use it for the sql connection should i also nest a further 'using' statement for a sql adapter? And then a further nested using for the DataSet?

using()
{
} 

A further addition to the question is if I want to use the same connection across several methods then is it best practice to have 'Using()' in each of the methods, or can I just create this connection object once?

like image 728
whytheq Avatar asked Nov 29 '22 17:11

whytheq


1 Answers

Something else that is worth pointing out is that you can combine multiple using statements into one block like this:

using (SqlConnection connection = new SqlConnection("connectionString"))
using (SqlCommand command = new SqlCommand("SELECT * FROM Users", connection))
{
    // Do something here...
}

Once you exit this block (either by reaching the end of the block or an exception was thrown), both the SqlConnection and SqlCommand object would be disposed automatically.

like image 86
Peter Monks Avatar answered Dec 05 '22 16:12

Peter Monks