简体   繁体   中英

c# IDataReader SqlDataReader difference

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM