5.2 Filling DataSets
Because DataSets are not tied to database data in any way, you may think of DataSets as simply
relational data stores. There is no requirement that you use database data to fill in a DataSet. In
practice, there are three ways to construct DataSets: from a DataAdapter (usually from a database),
from XML, and by constructing the DataSet manually.
5.2.1 Introducing DataAdapters
DataAdapters are the glue that connects DataSets to the underlying data stores. With DataAdapter,
you can fill the DataSet and update the data store from the DataSet. DataAdapters are essentially
meta-Command objects. The DataAdapter is composed of up to four Command objects. Each of
these Command objects does a specific job:
SelectCommand: Retrieves data from the data store
InsertCommand: Adds new records created in the DataSet to the underlying data store
UpdateCommand: Changes existing records in the data store based on changes in the DataSet
DeleteCommand: Deletes existing records in the data store based on deletions in the DataSet
The DataAdapter is used whenever the DataSet needs to interact directly with the data source. The
important concept here is that the DataAdapter holds Command objects for each of the basic
database operations, SELECT, INSERT, UPDATE, and DELETE. The idea behind the DataAdapter
is for it to be the bridge between the DataSet and the database. If the DataAdapter is that bridge, then
it must have the ability to do all the necessary database operations. As we continue to discuss the
DataSet throughout this chapter and the rest of Part 2 of this book, you will see how the DataAdapter
is used as a bridge.
One important job of the DataAdapter is to minimize the time a connection is open. You will notice
that throughout our use of DataAdapters, we never open and close the connection associated with our
DataAdapter. The DataAdapter knows that the connection needs to be as short-lived as possible and
handles all opening and closing of the connection. If we are using an already opened connection
when we use our DataAdapter, it will preserve the state of the connection (it will not open or close
the connection).
5.2.2 Creating a DataSet from a Database
In the most basic case, you would use the DataSet to hold a single table, as shown in Listing 5.1.
Listing 5.1 Creating a DataSet from the Database
...
// Create a Command object to query the entire Customer
table
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM CUSTOMER";
// Create a DataAdapter for use with filling a DataSet