【问题标题】:c# IDataReader SqlDataReader differencec# IDataReader SqlDataReader 区别
【发布时间】:2011-09-02 11:52:37
【问题描述】:

谁能告诉我这两段代码的区别?为什么要使用 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
    }
}

【问题讨论】:

    标签: c# sqldatareader idatareader


    【解决方案1】:

    SqlDataReader 实现了接口IDataReader。所有其他 ADO.NET 驱动程序(Oracle、MySql 等)也是如此。您可以使用IDataReader,这样如果您计划某天更改数据库引擎,您就不必重写所有SqlDataReader 引用。

    IDbConnectionIDbCommand 等也是如此。当然,当创建连接时,您需要指定您使用的引擎,但除此之外,您永远不必明确定义您使用的数据库引擎。

    注意IDataReader 没有HasRows 属性,您必须使用Create...() 方法来创建命令和参数:

    IDbCommand command = myDbConnection.CreateCommand();
    

    代替:

    SqlCommand command = new SqlCommand(myDbConnection);
    

    编辑:您可能希望使用抽象类 DbConnection 所有 ADO.NET 提供程序都继承自,而不是使用接口。它们提供了一些附加功能,例如获取模式信息,以及前面提到的DbDataReaderHasRows 属性。请参阅http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/759fa77b-8269-4c4a-be90-3c2bdce61d92/ 了解接口没有跟上抽象类的原因。

    【讨论】:

    • 很好的答案,你打败了我 :)
    【解决方案2】:

    IDataReader 和 IDataRecord 接口允许继承类实现 DataReader 类,该类提供读取一个或多个结果集的只进流For more details see this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-07
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多