Free mag vol1 | Page 888

CHAPTER 21  ADO.NET PART I: THE CONNECTED LAYER ShowConnectionStatus(cn); ... } Console.ReadLine(); } In this iteration, you create an instance of SqlConnectionStringBuilder, set the properties accordingly, and obtain the internal string using the ConnectionString property. Also note that you use the default constructor of the type. If you so choose, you can also create an instance of your data provider’s connection string builder object by passing in an existing connection string as a starting point (this can be helpful when you read these values dynamically from an App.config file). Once you have hydrated the object with the initial string data, you can change specific name/value pairs using the related properties, as in this example: static void Main(string[] args) { Console.WriteLine("***** Fun with Data Readers *****\n"); // Assume you really obta ined the cnStr value from a *.config file. string cnStr = @"Data Source=(local)\SQLEXPRESS;" + "Integrated Security=SSPI;Initial Catalog=AutoLot"; SqlConnectionStringBuilder cnStrBuilder = new SqlConnectionStringBuilder(cnStr); // Change timeout value. cnStrBuilder.ConnectTimeout = 5; ... } Working with Command Objects Now that you understand better the role of the connection object, the next order of business is to check out how to submit SQL queries to the database in question. The SqlCommand type (which derives from DbCommand) is an OO representation of a SQL query, table name, or stored procedure. You specify the type of command using the CommandType property, which can take any value from the CommandType enum, as seen here: public enum CommandType { StoredProcedure, TableDirect, Text // Default value. } When you create a command object, you can establish the SQL query as a constructor parameter or directly by using the CommandText property. Also when you create a command object, you need to specify the connection you want to use. Again, you can do so as a constructor parameter or by using the Connection property. Consider this code snippet: // Create command object via ctor args. string strSQL = "Select * From Inventory"; SqlCommand myCommand = new SqlCommand(strSQL, cn); 834