Name
CommandText
Synopsis
StringcommandText= Command.CommandText; Command.CommandText =commandText;
Defines the action that’s taken when this command
executes. The meaning of the CommandText property
depends on the value of the CommandType property.
If CommandType is Text (the
default), it’s the text of a SQL statement (such as
SELECT
*
FROM
Customers). If
CommandType is StoredProcedure,
it’s the name of the stored procedure
that’s executed. If CommandType
is TableDirect, it’s the name of
a table that’s returned or a comma-delimited list of
tables that’s joined and returned.
Example
The following example defines a Command and sets
the CommandText with a SQL INSERT statement. When
executed, this Command creates a new row.
string connectionString = "Data Source=localhost;" +
"Initial Catalog=Northwind;Integrated Security=SSPI";
string sQL = "INSERT INTO Categories (CategoryName, Description) " +
"VALUES ('Beverages', 'Soft drinks')";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = sQL;
int rowsAffected;
try
{
con.Open();
// Execute the command.
rowsAffected = cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}Notes
You can set two properties of the Command
object—the linked Connection and the
CommandText—using an overloaded constructor
when you create the Command:
SqlCommand cmd = new SqlCommand(commandText, con);
This is usually the easiest approach to setting these properties. You can then reuse the
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access