时间:2019-03-17 标签:c#IDataReaderSqlDataReader区别
有人可以告诉我这两段代码之间的区别吗?为什么使用IDataReader?
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// get data from the reader
}
}
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// get data from the reader
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SqlDataReader
实现接口IDataReader
。所有其他 ADO.NET 驱动程序(Oracle、MySql 等)也是如此。您可以使用IDataReader
,这样,如果您计划有一天更改数据库引擎,则不必重写所有SqlDataReader
引用。IDbConnection
、IDbCommand
等也是如此。当然,在创建连接时,您需要指定您使用的引擎,但除此之外,您永远不必显式定义您正在使用的数据库引擎。请注意,
IDataReader
没有HasRows
属性,您必须使用Create...()
方法来创建命令和参数:而不是:
编辑:您可能不想使用接口,而是使用所有 ADO.NET 提供程序继承的抽象类
DbConnection
。它们提供了一些附加功能,例如获取架构信息以及前面提到的DbDataReader
的HasRows
属性。请参阅http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/759fa77b-8269-4c4a-be90-3c2bdce61d92/ 了解为什么界面没有保留与抽象类一起。SqlDataReader
implements the interfaceIDataReader
. So do all other ADO.NET drivers (Oracle, MySql, etc). You can useIDataReader
, so that if you plan to change database engine some day, you don't have to rewrite all yourSqlDataReader
references.The same goes for
IDbConnection
,IDbCommand
, etc. Of course when creating the connection, you'll need to specify what engine you're using, but aside from that you'll never have to explicitly define which database engine you're using.Note that
IDataReader
does not have theHasRows
property, and you have to use theCreate...()
methods to create Commands and Parameters:Instead of:
EDIT: Instead of using the interfaces you may want to use the abstract class
DbConnection
all ADO.NET providers inherit from. They provide some additional features such as getting schema information, and the aforementionedHasRows
property for theDbDataReader
. See http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/759fa77b-8269-4c4a-be90-3c2bdce61d92/ for why the interface hasn't kept up with the abstract class.IDataReader 和 IDataRecord 接口允许继承类实现 DataReader 类,该类提供了一种读取一个或多个结果集的只进流的方法 有关更多详细信息,请参阅此
The IDataReader and IDataRecord interfaces allow an inheriting class to implement a DataReader class, which provides a means of reading one or more forward-only streams of result sets For more details see this