I've seen some people use SqlDataReader
to get data from database as
reader["Test"].ToString();
...
and others as
reader.GetString(0);
...
Is there any difference in any way? Or does it come down to personal preference?
I've seen some people use SqlDataReader
to get data from database as
reader["Test"].ToString();
...
and others as
reader.GetString(0);
...
Is there any difference in any way? Or does it come down to personal preference?
Pretty obvious:
GetValue
instead of GetString
and other typed methods. For me this way of accessing data is really useful only if your query something like 'select x, sum(y) from sometable` - i.e. second column has no name so you can't access it by name.Considered to performance - accessing by name takes slightly more time since accessing by index internally is
public override object this[int i]
{
get
{
return this.GetValue(i);
}
}
and accessing by name is
public override object this[string name]
{
get
{
return this.GetValue(this.GetOrdinal(name));
}
}
So accessing by name invokes GetOrdinal
first.
But in real application this difference is absolutely negligable.
It always makes sense to use field names instead of indices, because you could get some troubles, if the order of the fields in the SQL statement changes.
I prefer using this way: DataReader.GetString() via columnname