Database Reference
In-Depth Information
Figure 13-2. Displaying the SQL statement using CommandText
How It Works
The CommandText property returns a string, so you can display it just like any other string. The SQL
statement assigned to the CommandText property will return the Name and ProductNumber values of
products in the AdventureWorks Product table when you eventually execute it.
Note You must set both the Connection and CommandText properties of a command before the command can
be executed.
// Create command
SqlCommand cmd = new SqlCommand();
// Setting CommandText
cmd.CommandText = @"select Name,ProductNumber
from Production.Product";
You can set both of these properties when you create the command with yet another variation of its
constructor, as shown here:
// create command (with both text and connection)
String sql = @"select Name,ProductNumber from Production.Product";
SqlCommand cmd = new SqlCommand(sql, thisConnection);
This is equivalent to the previous code that assigns each property explicitly. This is the most
commonly used variation of the SqlCommand constructor, and you'll use it for the rest of the chapter.
 
Search WWH ::




Custom Search