Friday, 6 December 2013

READING AND WRITING DATA-----(DbCommand Object)

To execute commands to the database, you must have an open connection and a command
object. The previous lesson covered connectivity, and this lesson describes how to create and
use a command object.

Why do use the DBCommand Object?

I have collected some material on it.Let's know why do we use it?

We use the  DBCommand Object to send a Structured Query Language command to the datastore.
DbCommand can be a Data Manipulation Language (DML) command to retrieve,insert, update, or delete data.

The DbCommand object can also be a Data Definition Language (DDL) command, which enables you to create tables and modify schema information at the database. The DbCommand object requires a valid open connection to issue the command to the data store.

A DbConnection object can be passed into the DbCommand object’s constructor or attached to the DbCommand object’s Connection property after DbCommand is created, but the best way to create a


DbCommand object is to use the CreateCommand method on the DbConnection object so that provider-specific code is limited to the creation of the DbConnection object, and the DbConnection object automatically creates the appropriate provider-specific command object behind the scene.


DbCommand also requires a valid value for its CommandText and CommandType properties.The following code sample shows how to create and initialize a DbCommand object.

 C# Code:
var nw = ConfigurationManager.ConnectionStrings["nw"];
var connection = new SqlConnection(nw.ConnectionString);
var cmd = connection.CreateCommand();
 cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "CustOrderHist";
//don't forget to close the connection!


This code creates a DbConnection object that is an instance of SqlConnection. The DbConnection
object is then used to create a SqlCommand object, which is assigned to cmd.The DbConnection object must be opened before any command can be submitted. If it executes a stored procedure, the CommandText property contains the name of the stored procedure, whereas CommandType indicates that this is a call to a stored procedure.




No comments:

Post a Comment