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
}
}
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
SqlDataReader
implements the interfaceIDataReader
. So do all other ADO.NET drivers (Oracle, MySql, etc). You can useIDataReader
, so that if you plan to change database engine some day, you don't have to rewrite all yourSqlDataReader
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 theHasRows
property, and you have to use theCreate...()
methods to create Commands and Parameters:Instead of:
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 aforementionedHasRows
property for theDbDataReader
. 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.