Because C # is a garbage collector, and garbage collection is not deterministic. The fact is that your sqlconnection is located. You simply cannot choose when.
Sql links are a limited resource, and you can easily create enough of them to exhaust. Instead, write:
internal static DataSet SelectDataSet(String commandText, DataBaseEnum dataBase) { var dataset = new DataSet(); using (SqlConnection sqlc = dataBase == DataBaseEnum.ZipCodeDb ? new SqlConnection(ConfigurationManager.AppSettings["ZipcodeDB"]) : new SqlConnection(ConfigurationManager.AppSettings["WeatherDB"])) using (SqlCommand sqlcmd = sqlc.CreateCommand()) { sqlcmd.CommandText = commandText; var adapter = new SqlDataAdapter(sqlcmd.CommandText, sqlc); adapter.Fill(dataset); } return dataset; }
Although in this case, it can do for you, because the .Fill() method is a strange beast:
If IDbConnection is closed before calling Fill, it opens to retrieve data and then closes.
Thus, this means that the data adapter must take care of it for you if you start with a closed connection. It bothers me more that you pass the sql command as a simple string. From time to time, your queries should have user parameters, and this means that you combine this data directly into the command line. Do not do this!! Use SqlCommand Parameters instead.
Joel Coehoorn
source share