bigbiff
bigbiff

Reputation: 75

Get value from datareader

Given below is a sample piece of code I've written in VB.NET.

 commandReader.CommandText = "Select stu_id from tbl_students Where stu_id = 845)"
   dr = commandReader.ExecuteReader
   While dr.Read
        var_stu_id = dr!stu_id
        var_stu_id = dr.GetValue(dr.GetOrdinal("stu_id"))
        var_stu_id = dr("stu_id")
        var_stu_id = dr.GetValue("stu_id")
   End While
   dr.Close()

There are 4 ways of getting a particular value from a DataReader. I would like to know which is the best method among them(if anyone point out the difference between each of them then it'll be a great help).

Upvotes: 3

Views: 14291

Answers (2)

akhil kumar
akhil kumar

Reputation: 1618

The DataReader provides a series of methods that allow you to access column values in their native data types (GetDateTime, GetDouble, GetGuid, GetInt32, and so on).Using the typed accessor methods, assuming the underlying data type is known, reduces the amount of type conversion required when retrieving the column value.

Out of the 4 ways you have shown,the best method is var_stu_id = dr.GetValue("stu_id"). Because it Gets the value of the specified column in its native format.

Source: sqldatareader

data from datareader

Upvotes: 0

Mahadev
Mahadev

Reputation: 856

var_stu_id = dr.GetValue(dr.GetOrdinal("stu_id"))

Is the best method to Retrieve data from DataReader.

  1. Get<Datatype> functions used to retrieve specific DataType values from DataReader. But GetValue() can be used to retrieve any data type value.
  2. GetOrdinal() accepts index no of the column as well as Column Name as column reference which is a advantage of using this method from my point of view.
  3. I tried other methods before and By far this is the best method for me to retrieve data from DataReader. Other Method gave some exceptions like NullReferenceException while accessing columns.

Upvotes: 1

Related Questions