DbCommand Object (ADO.NET)

DbCommand object is used to send a SQL command to the data store. It 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 following sample shows how to create and initialize a DbCommand object.


C#

 
  Normal
  0
  
  
  
  
  false
  false
  false
  
  EN-US
  X-NONE
  X-NONE
  
   
   
   
   
   
   
   
   
   
   
   
   
  
  
   
   
   
   
   
   
   
   
   
   
   
  

 
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
 


 /* Style Definitions */
 table.MsoNormalTable
	{mso-style-name:"Table Normal";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-priority:99;
	mso-style-qformat:yes;
	mso-style-parent:"";
	mso-padding-alt:0in 5.4pt 0in 5.4pt;
	mso-para-margin-top:0in;
	mso-para-margin-right:0in;
	mso-para-margin-bottom:10.0pt;
	mso-para-margin-left:0in;
	line-height:115%;
	mso-pagination:widow-orphan;
	font-size:11.0pt;
	font-family:"Calibri","sans-serif";
	mso-ascii-font-family:Calibri;
	mso-ascii-theme-font:minor-latin;
	mso-hansi-font-family:Calibri;
	mso-hansi-theme-font:minor-latin;
	mso-bidi-font-family:"Times New Roman";
	mso-bidi-theme-font:minor-bidi;}

var ConnStr = ConfigurationManager.ConnectionStrings["myConnectionString"];

var myconnection = new SqlConnection(ConnStr.ConnectionString);

var myCommand = myconnection.CreateCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "EmpList";

Above code sample creates a DbConnection object that is an instance of SqlConnection. Then it creates a SqlCommand object named myCommand. When the CommandType property is set to StoredProcedure, the CommandText property should be set to the name of the stored procedure to be accessed.

CommandType Enumeration

  • Text : An SQL text command. (Default.)
  • StoredProcedure : The name of a stored procedure.
  • TableDirect : The name of a table.

Connection String in Web.config file

<connectionStrings>

<add name="myConnectionString" connectionString="Data Source=mySQLServer;Initial Catalog=myDatabase;User ID=myUserID;Password=myPassword" providerName="System.Data.SqlClient" />

</connectionStrings>