ExecuteReader ExecuteNonQuery ExecuteScalar Examples in Asp.NET when to use what to use in C#.NET

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Differences between ExecuteNonQuery, ExecuteReader and ExecuteScalar in asp.net
If you want to know about each sqlcommand object check below articles
ExecuteNonQuery
ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations.
Example:
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con=new SqlConnection(“Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB”))
{
con.Open();
SqlCommand cmd = new SqlCommand(“insert into UserInformation(UserName,FirstName,LastName,Location) values(@Name,@FName,@LName,@Location)”, con);
cmd.Parameters.AddWithValue(“@Name”, “Suresh Dasari”);
cmd.Parameters.AddWithValue(“@FName”, “Suresh”);
cmd.Parameters.AddWithValue(“@LName”, “D”);
cmd.Parameters.AddWithValue(“@Location”,”Chennai”);
int result= cmd.ExecuteNonQuery();
if(result>=1)
{
lblDetails.Text =  result.ToString();
}
else
{
lblDetails.Text = “0” ;
}
con.Close();
}

}

ExecuteScalar
Execute Scalar will return first row first column value i.e. it will return single value and ignore other values on execution of SQL Query or Stored procedure using command object.
Eample:
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(“Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB”))
{
con.Open();
SqlCommand cmd = new SqlCommand(“Select UserName,LastName,Location FROM UserInformation”, con);
string result = (string)cmd.ExecuteScalar();
if (!string.IsNullOrEmpty(result))
{
lblDetails.Text = result;
}
else
{
lblDetails.Text =  “No value Selected” ;
}
con.Close();
}
}
ExecuteReader

Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object.

Example:

// This method is used to bind gridview from database
protected void BindGridview()
{
using (SqlConnection con = new SqlConnection(“Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB”))
{
con.Open();
SqlCommand cmd = new SqlCommand(“Select UserName,LastName,Location FROM UserInformation”, con);
SqlDataReader dr = cmd.ExecuteReader();
gvUserInfo.DataSource = dr;
gvUserInfo.DataBind();
con.Close();
}

}


Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.