Free mag vol1 | Page 885

CHAPTER 21  ADO.NET PART I: THE CONNECTED LAYER // Create a SQL command object. string strSQL = "Select * From Inventory"; SqlCommand myCommand = new SqlCommand(strSQL, cn); // Obtain a data reader a la ExecuteReader(). using(SqlDataReader myDataReader = myCommand.ExecuteReader()) { // Loop over the results. while (myDataReader.Read()) { Console.WriteLine("-> Make: {0}, PetName: {1}, Color: {2}.", myDataReader["Make"].ToString(), myDataReader["PetName"].ToString(), myDataReader["Color"].ToString()); } } } Console.ReadLine(); } } Working with Connection Objects The first step to take when working with a data provider is to establish a session with the data source using the connection object (which, as you recall, derives from DbConnection). .NET connection objects are provided with a formatted connection string; this string contains a number of name/value pairs, separated by semicolons. You use this information to identify the name of the machine you want to connect to, required security settings, the name of the database on that machine, and other data provider–specific information. As you can infer from the preceding code, the Initial Catalog name refers to the database you want to establish a session with. The Data Source name identifies the name of the machine that maintains the database. Here, (local) allows you to define a single token to specify the current local machine (regardless of the literal name of said machine), while the \SQLEXPRESS token informs the SQL Server provider that you are connecting to the default SQL Server Express edition installation (if you created AutoLot on a full version of Microsoft SQL Server on your local computer, specify Data Source=(local)). Beyond this, you can supply any number of tokens that represent security credentials.