Izzy
Izzy

Reputation: 6876

Using SqlDataReader

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?

Upvotes: 0

Views: 67

Answers (2)

Andrey Korneyev
Andrey Korneyev

Reputation: 26886

Pretty obvious:

  • first one should be used when you know column names of data returned. For me it is preferred to second since column order can be changed. Also in this case you can convert datatype of returned objects later.
  • second one is preferable when you don't know these names (or maybe even columns has no names) but you're ensured in exact datatype of columns you're accessing. If column datatype will be mismatched - you'll get exception. So if you can't access colmn by name and not sure in exact datatype it's better to use 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.

Upvotes: 3

Juergen Gutsch
Juergen Gutsch

Reputation: 1764

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

Upvotes: 0

Related Questions