c#IDataReader与SqlDataReader的区别
有人能告诉我这两段代码之间的区别吗? 为什么要使用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 } }
SqlDataReader
实现了接口IDataReader
。 所有其他ADO.NET驱动程序(Oracle,MySql等)也是如此。 您可以使用IDataReader
,因此如果您计划某天更改数据库引擎,则不必重写所有SqlDataReader
引用。
对于IDbConnection
, IDbCommand
等也是如此。当然,在创建连接时,您需要指定您正在使用的引擎,但除此之外,您永远不必明确定义您正在使用的数据库引擎。
请注意, IDataReader
没有HasRows
属性,您必须使用Create...()
方法来创建命令和参数:
IDbCommand command = myDbConnection.CreateCommand();
代替:
SqlCommand command = new SqlCommand(myDbConnection);
编辑:您可能希望使用所有ADO.NET提供程序inheritance的抽象类DbConnection
而不是使用接口。 它们提供了一些额外的function,例如获取架构信息,以及DbDataReader
的上述HasRows
属性。 请参阅http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/759fa77b-8269-4c4a-be90-3c2bdce61d92/ ,了解接口未跟上抽象类的原因。
IDataReader和IDataRecord接口允许inheritance类实现DataReader类,它提供了一种读取一个或多个仅向前的结果集流的方法。 有关详细信息,请参阅此