我们怎样选择使用ExecuteReader, ExecuteNonQuery, ExecuteScalar ...

本文介绍了在ADO.NET中使用SqlClient命名空间针对MSSQL运行查询的三种基本方法:ExecuteReader、ExecuteNonQuery和ExecuteScalar,并详细解释了每种方法的最佳使用场景。

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 :)

http://blogs.x2line.com/al/archive/2007/05/01/3049.aspx

转载于:https://www.cnblogs.com/xuxiaoguang/archive/2008/03/10/1098607.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值