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 } } 
+8
c # sqldatareader
source share
2 answers

SqlDataReader implements the IDataReader interface. Thus, all other ADO.NET drivers (Oracle, MySql, etc.). You can use IDataReader , so if you plan to change the database engine once, you don’t have to rewrite all of your SqlDataReader links.

The same goes for IDbConnection , IDbCommand , etc. Of course, when creating a connection, you need to specify which engine you are using, but in addition to this, you will never have to explicitly determine which one you are using.

Note that IDataReader does not have a HasRows property, and you must use the Create...() methods to create the commands and parameters:

 IDbCommand command = myDbConnection.CreateCommand(); 

Instead:

 SqlCommand command = new SqlCommand(myDbConnection); 

EDIT: instead of using interfaces, you can use the abstract DbConnection class inherited by all ADO.NET providers. They provide some additional features, such as retrieving schema information and the aforementioned HasRows property for DbDataReader . See http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/759fa77b-8269-4c4a-be90-3c2bdce61d92/ , why the interface could not cope with the abstract class.

+16
source share

The IDataReader and IDataRecord interfaces allow the inheriting class to implement the DataReader class, which provides a means for reading one or more streams only for a direct set of For results; see more

+1
source share

All Articles