Command Object in ADO.NET



Command
:
Command is used to execute almost any SQL command from within the .net application. The SQL command like insert, update, delete, select, create, alter, drop can be executed with command object and you can also call stored procedures with the command object. Command object has the following important properties.

  • Connection : used to specify the connection to be used by the command object.
  • CommandType : Used to specify the type of SQL command you want to execute. To assign a value to this property, use the enumeration CommandType that has the members Text, StoredProcedure and TableDirect. Text is the default and is set when you want to execute ant SQL command with command object. StoredProcedure is set when you want to call a stored procedure or function and TableDirect is set when you want to retrieve data from the table directly by specifying the table name without writing a select statement.
  • CommandText : Used to specify the SQL statement you want to execute.
  • Transaction : Used to associate a transaction object to the command object so that the changes made to the database with command object can be committed or rollback.

Command object has the following important methods.

  • ExecuteNonQuery() : Used to execute an SQL statement that doesn’t return any value like insert, update and delete. Return type of this method is int and it returns the no. of rows effected by the given statement.
  • ExecuteScalar() : Used to execute an SQL statement and return a single value. When the select statement executed by executescalar() method returns a row and multiple rows, then the method will return the value of first column of first row returned by the query. Return type of this method is object.

  • ExecuteReader() : Used to execute a select a statement and return the rows returned by the select statement as a DataReader. Return type of this method is DataReader.