Friday, March 9, 2012

Defining connections as private variables

Is there any harm in defining a SqlConnection as a private class variable for a web page?

Private SqlConnection cn = new SqlConnectection(ConfigurationManager.ConnectionStrings["MyString"].ConectionString);

The connection is only opened in certain event handlers, and is closed right after use. It was always my understanding that creating the connection is not a big deal but opening the connection is.

Is that correct?I would declare the connection variables in the method that uses them. What happens when Method1 calls Method2 and both use that connection variable? Declaring them in as small a scope as possible makes lots more sense.

No comments:

Post a Comment