It doesn't matter which way you go.
SqlConnections are integrated by the operating system. You could literally open and close the connection thousands of times in a row and not be subject to any execution or other fines.
How it works:
- The application makes a request to create a db connection (
var c = new SqlConnection(...) ) - The operating system connection pool checks to see if the connection has a standby seat. If so, you will receive a link to it. If not, he spins a new one.
- The application indicates that it completed the connection (
c.Dispose() ) - The operating system keeps the connection open for a certain period of time if your application or another tries to create another connection with the same resource.
- If this connection remains inactive until the wait period has passed, the OS will finally close and free.
This is why, when connecting to the database for the first time, it may take a second to start before the commands can be processed. However, if you close it and open it again, the connection will be available immediately. More information here: http://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx
Now, as far as your code is concerned, usually you open 1 SqlConnection every time you call the SqlCommand; however, it is quite acceptable / reasonable to make several SqlCommand calls, being within the same block in the section of the SqlConnection clause.
Just keep in mind that you DO NOT want the SqlConnection object hanging in your code to last longer than absolutely necessary. This can lead to many potential problems, especially if you are a web developer. This means that it is much better for your code to open and close 100 SqlConnection objects in quick succession than to hold this object and pass it using various methods.
Notme source share