I have an old app that I’m supporting and I ran across the following Shared SQLConnection:
private static SqlConnection cnSQL = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString.ToString());
private static SqlCommand cmdSQL = new SqlCommand();
Now this connection is opened and closed everytime it’s needed, but it still get a sporatic error, and I believe this is because its being shared accross users (being static). Is my assumption correct? I believe I am much better off creating a new connection inside each method that needs it instead of having one per class. Or can I just remvoe the static option, and keep one connection per page and not have to worry about cross user contamination?
Thanks
Static members are shared between all the objects and methods of your code in the actual instance of your application but in no case between different users.
I would make the connection string static but not the connection itself. As you say, open a new connection in each method. Connection pooling will ensure that the physical connections will be kept open.
…
Make sure you are embedding the code in
using-statements. That way Resources are released even when an exception should occur.