When to use ExecuteScalar, ExecuteReader, and ExecuteNonQuery? [closed]

I am confused with the usage of

  1. ExecuteScalar
  2. ExecuteReader
  3. ExecuteNonQuery

when executing SQL queries in my code. When should I use each of these methods?


  • ExecuteScalar() only returns the value from the first column of the first row of your query.
  • ExecuteReader() returns an object that can iterate over the entire result set while only keeping one record in memory at a time.
  • ExecuteNonQuery() does not return data at all: only the number of rows affected by an insert, update, or delete.

Additionally, you can look at the DbDataAdapter type, which includes a Fill() method that allows you to download the entire resultset into a DataTable or DataSet object, as well as a number of other abilities.

Finally, this seems like a good time for you to get familiar with Microsoft Docs. This is what documentation is made for: you have the method names; go look them up.


ExecuteScalar : For Single Value

 Int32 Value = Convert.ToInt32(ExecuteScalar("SELECT SUM(COLUMNNAME) FROM TABLE")); 
 Int32 Value = Convert.ToInt32(ExecuteScalar("SELECT AVG(COLUMNNAME) FROM TABLE")); 

ExecuteReader : Row reading in forward mode

 IdataReader dr = ExecuteReader("SELECT * FROM TABLE"); 
 while(dr.Read())
 {
     //You will get rows values like this dr["ColumnName"]
 } 

ExecuteNonQuery : For Inserting/Deleting/Updating the rows into table

ExecuteNonQuery("DELETE FROM TABLE");
ExecuteNonQuery("UPDATE TABLE SET COLUMNNAME = 'A'");