If connecting to a database consumes a lot of resources, why should a database connection always be closed in your application if you have to open it again? Can I just make this connection available globally throughout my application so that other classes and methods can reuse it?
For example (in pseudo code):
public class PopulateGridViews()
{
public SqlConnection conn = new SqlConnection(@"Database:DATABASE");
conn.Open();
void PopulateGrid1()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM TABLE1");
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.Dispose();
// Populate Grid1
}
void PopulateGrid2()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM TABLE2");
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.Dispose();
// Populate Grid2
}
}
You should not leave connections open.
You should:
The connection itself is returned to the connection pool. Connections are a limited and relatively expensive resource. Any new connection you establish that has exactly the same connection string will be able to reuse the connection from the pool.
You should appropriately wrap anything that implements
IDisposablein ausingstatement block: