Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 373
bigbiff Avatar asked Dec 06 '25 07:12

bigbiff


1 Answers

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.
like image 56
Mahadev Avatar answered Dec 09 '25 01:12

Mahadev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!