I have a C# application that has been running just fine for the past year. However, in the past couple of months we have added more clients and the database has been reporting connection errors on a more consistent basis. It might be time to revisit the way connections are handled and perhaps there is a better way to do this. Here is the class that manages my connections:
public class myDAL
{
protected SqlConnection sqlConnection = new SqlConnection();
protected void openConnection(string connection)
{
sqlConnection.ConnectionString = connection;
sqlConnection.Open();
}
protected void closeConnection()
{
sqlConnection.Close();
}
}
Note that I’m really doing nothing special to manage the connection. I just call the open and close as needed and this is happening from multiple clients at the same time. Am I doing anything obviously wrong here?
Jim your practice of having open and close connection methods inside another class is very old, modern .NET development follows a patter like this nowadays:
see here: Closing SqlConnection and SqlCommand c# or search in SO for hundreds of questions and answers all telling the same, close the connection immediately either with a using like in this example or with a try/finally inside the same method, no need for one method to open and on method to close it, just prone to errors if anything happens in the between.