When should I open and close a connection to SQL Server
Posted
by Martin
on Stack Overflow
See other posts from Stack Overflow
or by Martin
Published on 2009-05-14T04:27:03Z
Indexed on
2010/04/30
2:27 UTC
Read the original article
Hit count: 288
I have a simple static class with a few methods in it. Each of those methods open a SqlConnection, query the database and close the connection. This way, I am sure that I always close the connection to the database, but on the other hand, I don't like to always open and close connection. Below is an example of what my methods look like.
public static void AddSomething(string something)
{
using (SqlConnection connection = new SqlConnection("..."))
{
connection.Open();
// ...
connection.Close();
}
}
Considering that the methods are inside a static class, should I have a static member containing a single SqlConnection? How and when should I drop it? What are the best practices?
© Stack Overflow or respective owner