Reputation: 75
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
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
Upvotes: 0
Reputation: 856
var_stu_id = dr.GetValue(dr.GetOrdinal("stu_id"))
Is the best method to Retrieve data from DataReader.
Get<Datatype>
functions used to retrieve specific DataType values from DataReader. But GetValue()
can be used to retrieve any data type value.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.NullReferenceException
while accessing columns.Upvotes: 1