C#的IDataReader SqlDataReader的区别 [英] c# IDataReader SqlDataReader difference

查看:3265
本文介绍了C#的IDataReader SqlDataReader的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我这两段代码的区别?为什么要使用IDataReader的?



 使用(IDataReader的读卡器= cmd.ExecuteReader())
{
,而( reader.Read())
使用{
//从读者
数据}
}

(SqlDataReader的读卡器= cmd.ExecuteReader() )
{
,而(reader.Read())
{
//从读者
获得的数据}
}


解决方案

SqlDataReader的实现接口的IDataReader 。所以,做其他所有ADO.NET驱动程序(Oracle,MySQL等,等)。您可以使用的IDataReader ,因此,如果您打算更改数据库引擎有一天,你不必重写所有的 SqlDataReader的引用。



这同样适用于的IDbConnection IDbCommand的等。当然,当的创建的连接,你需要指定你所使用的引擎,但除此之外,你永远不会有明确定义的数据库引擎,你'重新使用。



注意的IDataReader 不具有 HasRows 属性,你必须使用创建...()方法来创建命令和参数:

  IDbCommand的命令= myDbConnection.CreateCommand(); 



而不是:

 的SqlCommand命令=新的SqlCommand(myDbConnection); 



编辑:使用接口代替,你可能要使用抽象类的DbConnection 所有ADO.NET提供继承。他们提供一些额外的功能,如获取模式信息,和上述 HasRows 属性的 DbDataReader 。请参见 http://social.msdn.microsoft。 COM /论坛/ EN-US / adodotnetdataproviders /线程/ 759fa77b-8269-4c4a-be90-3c2bdce61d92 / 为什么接口没有与抽象类跟上。


Can someone tell me the difference between these two pieces of code? Why use 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 implements the interface IDataReader. So do all other ADO.NET drivers (Oracle, MySql, etc). You can use IDataReader, so that if you plan to change database engine some day, you don't have to rewrite all your SqlDataReader 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 the HasRows property, and you have to use the Create...() methods to create Commands and Parameters:

IDbCommand command = myDbConnection.CreateCommand();

Instead of:

SqlCommand command = new SqlCommand(myDbConnection);

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 aforementioned HasRows property for the DbDataReader. 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.

这篇关于C#的IDataReader SqlDataReader的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆