Reputation: 6203
In examples of interacting with the database in ASP.NET I always see
using ( SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString) )
{
// ... Do some stuff
}
but I'm wondering, shouldn't I just be connected all the time? It doesn't make sense why I would want all the overhead involved in opening and closing connections. Shouldn't con
be like a static
member of my model?
Upvotes: 2
Views: 2576
Reputation: 801
In my experience, you do not want to leave a connection open if you are not using it. It is much cleaner to use a Using statement when connecting to a DB. There is a good discussion here... https://stackoverflow.com/questions/7072583/is-it-ok-to-leave-a-sql-connection-open
Upvotes: 2
Reputation: 887453
SqlConnection
is not thread-safe.
Since ASP.Net requests can arrive on multiple threads, you must not do that.
SqlConnection is already pooled; you don't have anything to worry about.
Upvotes: 12