Question: Accessing a field in datareader

  • Thread starter Thread starter Miha Markic
  • Start date Start date
M

Miha Markic

Hi,

VB Programmer said:
When referring to a field in a datareader which is better, to refer to it by
using a numeric index, or the name of the field? Of course, using the name
is more readable, but isn't it slower? What are the pros/cons?

Yes, accessing it by number is faster and less readible unless you use an
enumeration or a variable with descriptive name instead of numbers.
 
A hybrid approach works well, and should only have a minimal impact on
performance, since the string-lookup only occurs once at the beginning of
the loop. This approach should handle re-ordering of columns in a query,
but it won't handle renaming of columns (which *should* rarely
happen---although there are approaches for handling this as well, such as
keeping the field names as constants elsewhere).


string commandText = "SELECT Contacts.ContactID, Contacts.LastName FROM
Contacts";
using(SqlConnection connection = new SqlConnection(connectionString))
{
using(SqlCommand command = new SqlCommand(commandText, connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
int contactID = reader.GetOrdinal("ContactID");
int lastName = reader.GetOrdinal("LastName");
while (reader.Read())
{
Console.WriteLine("{0}: {1}", reader.GetInt32(contactID),
reader.GetString(lastName));
}
}
}
}
 
When referring to a field in a datareader which is better, to refer to it by
using a numeric index, or the name of the field? Of course, using the name
is more readable, but isn't it slower? What are the pros/cons?

Thanks!
Robert
 
Back
Top