Sunday, April 2, 2017

Difference in ExecuteNonQuery ExecuterReader ExecuteScalar

ExecuteNonQuery() Vs ExecuterReader() Vs ExecuteScalar()
Today we will check the difference between ExecuteNonQuery, ExecuterReader and ExecuteScalar and we will try to understand which one should be used for which type of Database operations:
1. ExecuteNonQuery():
ExecuteNonQuery is always recommended for such operation in which you are not required to return anything from the query. it's used for INSERT,UPDATE and DELETE operations or other Action Queries like Alter, Drop,Create. it's function is same either we use direct SQL Query or Stored Procedure. so becarefull and do not use with SELECT Statements because it will always return total count of affected rows by query or stored procedure. we can not do much with its return because it is only returning int and its assigned to integer variable only.
Example:
        ExecuteNonQuery("DELETE FROM MYTABLE");
    ExecuteNonQuery("UPDATE TABLE SET COLUMNAL = 'Code'");

If we use ExecuteNonQuery with a Select Statement then it will do nothing. it will execute the Query but it's row affected will be negative -1 you can throw any error also.

2. ExecuterReader():
ExecuteReader is used to Read the Data from SQL Statement and its recommended to use with SELECT Operations. ExecuteReader returns IDataReader object when fetch the records from Database and we can perform other operation on this object as per our requirements like we can bind GridView etc. we use .Read() method of SqlDataReader which read the data one by one. it will also work for Action Queries but best to use for SELECT non action queries. it will return a collection of all data on which we can perform operation row by row or column by column also.

       IDataReader dr = ExecuteReader("SELECT * FROM MYTABLE"); 
     while(dr.Read())
     {
             Response.Write("Name: " + dr["ColumnName"]);
    } 


3. ExecuteScalar():
ExecuteScalar is always used for a single column value. it will return first column of first row of Query. it is used when we are required one column or a single value like we want to get SUM of a column,Average of Column or Count and also it's usable when we want to know ID of employee from employees table against a single employee. it will be usefull for Non Action quries. it will return the an object type.

       Int32 Value = Convert.ToInt32(ExecuteScalar("SELECT SUM(SALARY) FROM EMPLOYEES")); 
 Int32 Value = Convert.ToInt32(ExecuteScalar("SELECT AVG(INCENTIVE) FROM EMPLOYEES")); 


it's always used for single value but if we used with multiple column statement then it's behavior will also remain same it will return first row first column value.
Comments and Suggestions are Always Welcome!

No comments:

Post a Comment