vb.net 从数据读取器获取价值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29619822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:00:42  来源:igfitidea点击:

Get value from datareader

vb.netdatareader

提问by bigbiff

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

下面给出的是我用 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).

有 4 种方法可以从DataReader. 我想知道哪种方法是其中最好的(如果有人指出它们之间的区别,那么这将是一个很大的帮助)。

回答by Mahadev

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

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

Is the best method to Retrieve data from DataReader.

是从 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 noof the column as well as Column Nameas 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 NullReferenceExceptionwhile accessing columns.
  1. Get<Datatype>用于从 DataReader 检索特定 DataType 值的函数。但GetValue()可用于检索任何数据类型值。
  2. GetOrdinal()接受列的索引号以及列名作为列引用,从我的角度来看,这是使用此方法的优势。
  3. 我之前尝试过其他方法,到目前为止,这是我从 DataReader 检索数据的最佳方法。其他方法给出了一些例外,例如NullReferenceException访问列时。

回答by akhil kumar

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.

DataReader 提供了一系列方法,允许您访问其本机数据类型(GetDateTimeGetDoubleGetGuidGetInt32等)的列值。使用类型化访问器方法(假设基础数据类型已知)可减少检索列值时所需的类型转换量。

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.

在您展示的 4 种方法中,最好的方法是var_stu_id = dr.GetValue("stu_id")。因为它以本机格式获取指定列的值

Source: sqldatareader

来源:sqldatareader

data from datareader

来自数据读取器的数据