when we want to connect to database from visual studio should we always check(before using another query) that if our connection is open,close it and again open it??
if(connection is open){
close connection;
}
open connection for another use;
Assuming you’re using .NET, you should generally open and close the connection for each logical operation. If you’re doing multiple queries in the same code path (i.e. you know you’re about to do another query) then it makes sense to leave the connection open, but I wouldn’t leave it open “just in case”.
Bear in mind that the connection pooling in .NET makes it reasonably cheap to “open a connection” as the network connection will still be up anyway. Typically you’d use something like:
The
usingstatement will “close the connection” (read: return it to the connection pool) automatically when you’re done.Keeping each query (or set of queries) logically separate means it’s harder to end up with race conditions, threading issues etc. I wouldn’t recommend keeping a connection as a global variable or anything like that.
Of course, if you’re using something like LINQ to SQL the connection handling is likely to be mostly done for you.