c# IDataReader SqlDataReader区别

标签 c# sqldatareader idatareader

谁能告诉我这两段代码的区别?为什么要使用 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 实现接口(interface)IDataReader。所有其他 ADO.NET 驱动程序(Oracle、MySql 等)也是如此。您可以使用 IDataReader,这样如果您打算某天更改数据库引擎,就不必重写所有的 SqlDataReader 引用。

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

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

IDbCommand command = myDbConnection.CreateCommand();

代替:

SqlCommand command = new SqlCommand(myDbConnection);

编辑:您可能希望使用所有 ADO.NET 提供程序继承自的抽象类 DbConnection 而不是使用接口(interface)。它们提供了一些额外的功能,例如获取架构信息,以及前面提到的 DbDataReaderHasRows 属性。参见 http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/759fa77b-8269-4c4a-be90-3c2bdce61d92/为什么接口(interface)跟不上抽象类。

关于c# IDataReader SqlDataReader区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6137245/

相关文章:

c# - 在C#中查找较大字符串中子字符串的所有位置

c# - ADO.NET 问题 : When to use DataReader, DataAdapter

c# - 使用DataReader调用带参数的存储过程

c# - 桌面软件中的 Onenote OCR 功能

c# - 处理嵌套的一次性元素?

c# - 本地化 Win7 版本上的 UI 截断

c# - SqlDataReader 索引器性能

c# - SqlDataReader 获取特定的 ResultSet

c# - 阅读 WebApi 的 IDataReader 的最佳方式

c# - 检查数据读取器中是否存在列