Tagged with DataAdapter
I always forget this blog this, but when I am doing a database project using Typed DataSets, I almost always use a Component Surface to build my DataAdapters interactively. For example:
Here I add a component to my project:
I have been reviewing a bunch of code that utilizes ADO.NET's DataAdapters. This code has been some samples that are on the Internet, some questions directly to http://wildermuth.com and others from DevelopMentor's .NET Mailing Lists. One thing I have noticed is that much of that code is opening the database connection before using the DataAdapter to fill a DataSet.
This does work, but there seems to be some confusion about how this should work. In fact, under the covers all DataAdapters open and close the database if it has not already been done. This is because the DataAdapter knows when to open and close the connection to the database to minimize the length of time that the precious resource (the connection) is actually open. This is what the code looks like that I've been reviewing:
// Create the DataSet DataSet dataSet = new DataSet(); // Create the Connection SqlConnection conn = new SqlConnection("..."); // Create the Command SqlDataAdapter adapter = new SqlDataAdapter("...", conn); // Open the Connection conn.Open(); // Fill the DataSet adapter.Fill(dataSet); // Close the Connection conn.Close();
In reality, you don't need to open the close the connection before using it with an adapter. If the connection is closed, it will open it and close it as soon as it is done with the connection. I would expected to see more code that looked like this: