ExecuteReader, ExecuteNonQuery, ExecuteScalar ... When to use What ?
SqlClient namespace in ADO.NET provides 3 basic methods to run queries with SqlCommand against MSSQL:
- ExecuteReader
- ExecuteNonQuery
- ExecuteScalar
.NET Framework is around for 5 years already now, but these 3 methods are among the most misused in application development. The problem is that ExecuteReader will work for every query via SqlCommand, so most people use it everywhere. The direct result - slow and non-scalable solution. Other results include database bottlenecks, locks and connection leaks.
So I decided to provide a small cheat-sheet that clearly demonstrates when to use each method.
ExecuteReader
Do not use: when database query is going to provide for sure exactly 1 record. It may be getting record by its id (which is PK in the database) - GetOrderById and such. In this case use ExecuteNonQuery with output parameters.
Use: when database query is going to provide a set of records. It may be search or report.
ExecuteNonQuery
Use: when we are talking about a single database record - in Update, Insert, Delete and Get by Id. In all these cases we can use input/output/input-output parameters. Please note that from the application architecture point of view it is also good practices when your Insert and Update stored procedure returns changed record exactly like Get By Id method does.
ExecuteScalar
Do not use: when database query returns a single value and this value can be defined as parameter in T-SQL. ExecuteNonQuery with output parameter(s) is always preferred in this case since it is more flexible, tomorrow there will be 2 values therefore having ExecuteNonQuery we do not need to change method signatures.
Use: when database query returns a single value and this value cannot be defined as output parameter, because of T-SQL type limitation for variables. For example type image cannot be output parameter in MSSQL.
The most common example for ExecuteScalar is fetching a single image stored in the database and converting it to array of bytes. If you google it - most examples will demonstrate using of ExecuteReader to accomplish image handler, however ExecuteScalar will be more scalable and faster.
Conclusion
Always use ExecuteNonQuery except: when you have a set of records - use ExecuteReader and when you have a single output value that cannot be defined as a parameter - use ExecuteScalar. Hope this helped to clarify something. Enjoy :)
Tuesday, May 1, 2007 9:58 PM