Friday, May 1, 2009

Difference between ExecuteNonQuery, ExecuteScaler, ExecuteReader

Difference Angle

ExecuteNonQuery

ExecuteScaler

ExecuteReader

About

After Executing Sql statement Returns number of rows affected

Returns Single value, Executes first column first row only

Send the Command text to connection and builds a SqlDataReader.

When we use

ExecuteNonQuery is used to perform Catalog operation like Creating table in database or Changing of data in tables (without using Dataset) by using Insert, Update, Delete, create

Selecting only single fields like count field

When we manipulating with DataReader it used, Sending SQL Select statements to a database, Invoking Stored Procedures

Example

Example:
SqlCommand cmd = new SqlCommand("Insert Into SampleTable Values('1','2')",con);
//con is the connection object

con.Open();
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed
This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of DML commands.

Example : select count(*) from emp

ExecuteScalar is used to get aggregate value. ExecuteScalar will return only one value that is first column value of the first row in the executed query.

Example 2:
cmd.CommandText = "Select Name, DOB, from Emp where ID=1";
Dim strName As string = cmd.ExecuteScalar.ToString
This returns one value only, no recordsets.

Example:
SqlConnection con = new SqlConnection(constr);
//constructor can be connection of string.
SqlCommand cmd = new SqlCommand ("select * from emp", con);
con.Open();
SqlDataReader dr = cmd. ExecuteReader (CommandBehavior. CloseConnection);

while(dr.Read())
{
Console.WriteLine (dr.GetString(0));
}
dr.Close();

//Implicitly closes the connection because CommandBehavior. CloseConnection was specified.
ExecuteReader is used to get set records by specified query

No comments:

Post a Comment