Datasheet
Next, we have the connection string that simply points to our existing database:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
"Ole DB Services=-4; Data Source=C:\\BegASPNET11\\" +
"data\\Northwind.mdb";
Notice that this uses two backward slash characters to avoid the problem of the single slash character
being an escape sequence. In our earlier example we used the
@ symbol.
Now we have the connection object:
System.Data.IDbConnection dbConnection =
new System.Data.OleDb.OleDbConnection(connectionString);
One thing that's immediately obvious is the fact that this example doesn't use the OleDbConnection
type to define the connection to the database; it uses IDbConnection. If this seems confusing, refer to
the discussion of interfaces in the previous chapter, where we talked about generic routines.
IDbConnection is an interface that defines what the Connection class must do, and since the wizard is
building a generic routine, it uses this interface. This is because the wizard allows you to connect to
different database types. This is seen on the first screen and is the same as the
Data Explorer allowing you
to pick either Access or SQL Server database. To make the wizard simpler, it uses the generic interface as
the type rather than having to use the type for a specific database.
The Interface simply enforces the correct signature on a class implementing the interface. There's no
actual requirement for the implementation to do anything. You could have a class that implements the
Open() method but that actually does something else instead of opening a connection. It would be
dumb, but it could be done.
Next we have the SQL string, as built up by the wizard:
string queryString = "SELECT [Products].[ProductName], " +
"[Categories].[CategoryName] FROM [Products], [Categories] " +
"WHERE ([Categories].[CategoryID] = [Products].[CategoryID])";
Now we have the definition of the command object. In previous examples, we passed the command text
directly into the
OleDbDataAdapter. Underneath, ASP.NET actually creates another object – a Command
object. However, you don't see that Command object, as it is used internally. The wizard creates the
Command object directly, by making use of the CommandText property to store the SQL command, and
the
Connection property to store the database connection. As with the connection that used the
interface as its type, the command is also defined as an interface type (
IDbCommand).
System.Data.IDbCommand dbCommand = new System.Data.OleDb.OleDbCommand();
dbCommand.CommandText = queryString;
dbCommand.Connection = dbConnection;
Now we have the definition of the data adapter, and as with the connection, the type of the variable is
the interface type:
System.Data.IDbDataAdapter dataAdapter =
new System.Data.OleDb.OleDbDataAdapter();
268
Chapter 8
57084_08.qxp 30/01/2004 8:03 PM Page 268