IDataReader

  • Thread starter Thread starter RP
  • Start date Start date
R

RP

I saw a code in a class where IDataReader is used to retrieve result
from query, even if only one column is to be retrieved. It uses a
CommandObject with ExecuteReader but not using ExecuteScalar.

For what IDataReader is used and what are the benefits of it as
compared to sime DataReader.
 
If you need a single value, use ExecuteScalar.

You can get a single value with ExecuteReader ..... but its unnecessary
overhead.

..........

Using IDataReader (which is hte interface) will allow you to future proof
your code, as in the future you could swap out
(for example)
OleDbReader for a SqlReader instead.

Its a basic OO concept.

IDataReader GetEmployees()
{
//this procedure could return either an OleDbReader, a SqlReader, a
OracleReader (sp??) or anything else that implements IDataReader

}


I code to the interface, even though I use a SqlReader 99.9% of the time.
 
How ExecuteScalar be used with IDataReader? 99% chance is that the
user will work on one database itself.
 
One other advantage of IDataReader would be when working with BLOB/
CLOB data; ExecuteReader can be used in sequential mode to read large
data more efficiently - i.e. in chunks rather than the either column
at once.

Another use might be when you want to verify that the data is
*exactly* as expected; in LINQ terms, ExecuteScalar is comparable to
"First" - where-as if you want to enforce a "Single" you need to check
that no *more* rows were received.

I haven't checked whether ExecuteScalar does this - but another issue
with db access is where a database error message *follows* the data-
stream. Because of how TDS works, you won't see the database error
unless you at the minimum ask the reader to read past its grids - i.e.
"while (dr.NextResult()) {...}". This scenario would be quite rare,
but it bit me once and I haven't forgotten it. The man page suggests
that ExecuteScaler simply stops reading once it has found an answer.

Getting less likely: you might have a common logging block that tracks
the data volumes returned; in the *general* case this might work with
IDataReader?

There are some other edge-case occasions when it might also be useful
- i.e. when you want to give it to something existing that expects an
IDataReader (perhaps it normally works with lots of data, and you just
happen to be giving it one cell). Two main examples here would be
object pipelines, and things like SqlBulkCopy [which would be overkill
for a single cell!].

Marc
 
Back
Top