Você está na página 1de 1

SqlClient namespace in ADO.

NET provides 3 basic methods to run queries with SqlC ommand 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 w ill work for every query via SqlCommand, so most people use it everywhere. The d irect result - slow and non-scalable solution. Other results include database bo ttlenecks, locks and connection leaks. So I decided to provide a small cheat-sheet that clearly demonstrates when to us e each method. ExecuteReader Do not use: when database query is going to provide for sure exactly 1 record. I t may be getting record by its id (which is PK in the database) - GetOrderById a nd 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, Del ete and Get by Id. In all these cases we can use input/output/input-output param eters. Please note that from the application architecture point of view it is al so good practices when your Insert and Update stored procedure returns changed r ecord exactly like Get By Id method does. ExecuteScalar Do not use: when database query returns a single ined as parameter in T-SQL. ExecuteNonQuery with referred in this case since it is more flexible, therefore having ExecuteNonQuery we do not need value and this value can be def output parameter(s) is always p tomorrow there will be 2 values 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 exampl e type image cannot be output parameter in MSSQL. The most common example for ExecuteScalar is fetching a single image stored in t he database and converting it to array of bytes. If you google it - most example s will demonstrate using of ExecuteReader to accomplish image handler, however E xecuteScalar will be more scalable and faster. Conclusion Always use ExecuteNonQuery except: when you have a set of records - use ExecuteR eader and when you have a single output value that cannot be defined as a parame ter - use ExecuteScalar. Hope this helped to clarify something. Enjoy :)

Você também pode gostar