Now here in this tutorial, I’ll explain top main difference between ExecuteReader, ExecuteNonQuery and ExecuteScalar in detail with example.
In my previous tutorials, I’d explained simple insert update and delete, gridview inline insert update delete, difference between dataset datareader dataadapter and dataview and other more cracking tutorials on Difference, Gridivew, Asp.net here.
Differences between ExecuteReader, ExecuteNonQuery and ExecuteScalar:
The SqlCommand ExecuteReader in Ado.net is used to get and read the set of rows fetched using sql queries or stored procedures from the sql database table.
ExecuteReader object is a forward-only and supports read-only access of queried results that fetched from the database tables cannot be modified as it always opens in read-only mode.
In short, ExecuteReader is generally used to get or read data from resultset so it’s appropriate with SELECT Command.
The SqlCommand ExecuteNonQuery in Ado.net returns number of row(s) affected while performing sql operations like INSERT, UPDATE, DELETE etc.
ExecuteNonQuery return -1 if there is no row affected, otherwise return int value indicating number of rows/columns affected while performing sql operation.
In short, ExecuteNonQuery is generally used when we want to perform any operation on resultset so it’s appropriate with INSERT, UPDATE, DELETE Command.
The SqlCommand ExecuteScalar in Ado.net returns first column’s first cell value of the first row from the resultset returned by the sql query or stored procedure, meaning return only single value and additional columns or rows are ignored.
ExecuteScalar will return null reference if resultset is empty, and can returns a maximum of 2033 characters.
In short, ExecuteScalar is generally used when we need only first value of resultset or aggregate functions like SUM, COUNT, AVG etc in SELECT Command.
These are the common differences that we need to clear before using them. If you have any queries please leave comment below, I’ll try my best to reply you soon.