Does SqlDataAdapter close the SqlConnection after the Fill() function or do I need close it myself?
string cnStr = @"Data Source=TEST;Initial Catalog=Suite;Persist Security Info=True;User ID=app;Password=Immmmmm";
cn = new SqlConnection(cnStr);
SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Date", cn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
cn.Close() // ????????
Console.WriteLine(ds.Tables[0].Rows.Count);
Console.WriteLine(cn.State);
In your current usage, it will close for you:
http://msdn.microsoft.com/en-us/library/zxkb3c3d.aspx
I think it's always better to explicitly cater for it yourself with a
usingstatement:This is often more readable and doesn't rely on people understanding the inner workings of
SqlDataAdapter.Fill, just theusingstatement and connections.However, if you know the connection is closed before the adapter uses it (as in, you've just created the connection) and it's not used for anything else, your code is perfectly safe and valid.
Personally, I'd write something like this: