Describe the command object and its method.

Answer

After successful connection with database you must execute some sql query for manipulation of data or selecting the data. This job is done by command object. If you are using SQL Server as database then SqlCommand class will be used. It executes SQL statements and Stored Procedures against the data source specified in the Connection Object. It requires an instance of a Connection Object for executing the SQL statements.

- ExecuteReader: This method works on select SQL query. It returns the DataReader object. Use DataReader read () method to retrieve the rows.
- ExecuteScalar: This method returns single value. Its return type is Object
- ExecuteNonQuery: If you are using Insert, Update or Delete SQL statement then use this method. Its return type is Integer (The number of affected records).

using System;
using System.Data;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
          protected void Page_Load(object sender, EventArgs e)
          {
                  SqlConnection con = new SqlConnection("Data Source=Your data source name;Initial Catalog=Demo;Integrated Security=True");
                  SqlCommand cmd = new SqlCommand();
                  cmd.Connection = con;
                  cmd.CommandText = "select * from employee";
                  cmd.CommandType = CommandType.Text;
                  con.Open();
                  SqlDataReader reader = cmd.ExecuteReader();
                  if (reader.HasRows) 
                  {
                          while (reader.Read()) 
                  {
                          DropDownList1.Items.Add(reader[1].ToString());
                   }
           }
          else
          {
                Label1.Text="No rows found.";
           }
           reader.Close();
           con.Close();
       }
}

In the above given example a DropdownList has been taken that is filled by second column of employee table

All ado.net Questions

Ask your interview questions on ado-net

Write Your comment or Questions if you want the answers on ado-net from ado-net Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---