Datasheet

On the left we have the database and the connection, in the middle we have four Command objects, and
on the right a
DataAdapter and a DataSet. Notice that the DataAdapter contains four Command
objects:
SelectCommand: Fetches data
UpdateCommand: Updates data
InsertCommand: Inserts new data
DeleteCommand: Deletes data
Each of these
Command objects has a Connection property to specify which database the command
applies to, a
CommandText property to specify the command text to run, and a CommandType property to
indicate the type of command (straight SQL or a stored procedure).
As we said earlier, if you don't explicitly create
Command objects and use the DataAdapter directly, a
Command is created for you using the details passed into the constructor of the DataAdapter, and this
Command is used as the SelectCommand.
We'll be looking at the
UpdateCommand, InsertCommand, and DeleteCommand in the next chapter.
Let's look at these objects in a bit more detail, concentrating on the
OleDb ones as we're using Access. If
you want to use SQL Server, you can simply replace
OleDb with SqlClient in the object names; just
change the connection string, and continue working.
The OleDbConnection Object
As we've said earlier, the Connection object provides us with the means to communicate to a database.
Probably the only property you'll use is the
ConnectionString property that can either be set as the
object is instantiated:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=C:\\BegASPNET11\\data\\Northwind.mdb";
OleDbConnection conn = new OleDbConnection(connectionString);
or it can be set with the property:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=C:\\BegASPNET11\\data\\Northwind.mdb";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = connectionString;
The two main methods you'll use are Open() and Close(), which (unsurprisingly) open and close the
connection to the database. When used as we have so far, there is no need to do this explicitly since the
Fill() method of a DataAdapter does it for you.
The OleDbCommand Object
The OleDbCommand has several properties that we'll be looking at:
271
Reading from Databases
57084_08.qxp 30/01/2004 8:03 PM Page 271