When I connect to a SQL datasource in my C# application, I can fill a dataset using the following code. Note that I am not explictly opening a connection to the datasource.
SqlConnection cw_con = new SqlConnection("Server=Server;Database=Database;User=User;password=password");
SqlCommand cmd = new SqlCommand("SELECT * FROM Example WHERE value = value");
cmd.Connection = cw_con;
//Create DataSet
DataSet cw_ds = new DataSet("cw_ds");
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
//Execute Command and Fill DataSet
da.Fill(cw_ds);
cw_ds.Clear();
However, If I want to execute a nonquery such as a INSERT INTO or UPDATE why do I have to explicitly open the connection by using connection.Open();?
SqlConnection cw_con = new SqlConnection("Server=Server;Database=Database;User=User;password=password");
cw_con.Open();
SqlCommand cmd = new SqlCommand("UPDATE example SET value = value WHERE value = value");
cmd.Connection = cw_con;
cmd.ExecuteNonQuery();
cw_con.Close();
That is because a
DataAdapteropens the connection implicitely when it’s closed initially. It’ll close it afterwards if it was closed before, otherwise the connection stays open.From MSDN:
When using a
SqlCommandyou must explicitely open and close connections yourself.As a side note:
IDisposable, especially Connections since it ensures that it gets disposed/closed as soon as possible, even in the case of an error