Tuesday, May 5, 2009

Explain Command Object

It allows to manipulate database by executing stored procedure or sql statements.

A SqlCommand object allows us to specify what type of interaction we want to perform with a database.

For example, we can do select, insert, update, and delete commands on rows of data in a database table.

For Selecting data from datatable

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);

// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();

Example:

For Inserting data in datatable

// prepare command string

string insertString = @"insert into Categories(CategoryName, Description) values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";

// 1. Instantiate a new command with a query and connection

SqlCommand cmd = new SqlCommand(insertString, conn);

// 2. Call ExecuteNonQuery to send command

cmd.ExecuteNonQuery();


No comments:

Post a Comment