Saturday, November 21, 2009

What is a command object in ADO.NET. How to use a command object in .NET?

ADO.NET Command Object - The Command object is similar to the old ADO command object. It is used to store SQL statements that need to be executed against a data source. The Command object can execute SELECT statements, INSERT, UPDATE, or DELETE statements, stored procedures, or any other statement understood by the database. See sample code...

'Code below in VB.NET
...
Dim ObjCom as SqlClient.SqlCommand
ObjCom.SqlConnection(strCon)
ObjCom.Connection.Open()
ObjCom.CommandText = "Select * from tblSample"
ObjCom.ExecuteNonQuery()

SqlCommand objects are not used much when we use datasets and data adapters. Following are some properties of the SqlCommand class...

Connection Property - This property contains data about the connection string. It must be set on the SqlCommand object before it is executed. For the command to execute properly, the connection must be open at the time of execution.

CommandText Property - This property specifies the SQL string or the Stored Procedure.

objCom.CommandText = "Insert into Employees (empid, empname) values ('EMI0334','Mandy')"

Paramaters Collection - If we want to update values in the Employees table above, but we do not know the values at design time, we make use of placeholders. These are variables prefixed with "@" symbol. Our code will look like this...

objCom.CommandText = "Insert into Employees (empid, empname) values (@empid, @empname)

Next, we have to create parameters that will be used to insert values into the placeholders. For this, we need to add parameters to the parameters collection of the SqlCommand object. This is done so that the values added through the parameters collection & placeholders get i ncluded in the SQL statement. Here, parameters mean the parameters to be passed to the SQL statement/Stored Procedures, not the method's parameters.

In order to add parameters to the SqlCommand object, we write the following code...

objCom.CommandText = "Insert into Employees (empid, empname) values (@empid, @empname)"

objCom.Parameters.Add("@empID", txtempid.text)

objCom.Parameters.Add("@empname", txtempname.text)

ExecuteNonQuery Method - Once the connection is open, we run the query in the SqlCommand object using the ExecuteNonQuery method. This is very simple as shown below...

objConnection.Open()
objCom.ExecuteNonQuery()
objConnection.Close()

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home