.NET SqlDataReader的项目[]对的GetString(GetOrdinal())?项目、SqlDataReader、NET、GetString

2023-09-03 00:49:22 作者:念与北诗°

使用 SqlDataReader的类,什么,如果有的话,是功能差异:

 (串)的DataReader [MyFieldName];
 

  dataReader.GetString(da​​taReader.GetOrdinal(MyFieldName));
 

解决方案

铸造问题放在一边,为单一的呼叫,有没有。索引器会打电话到DbDataReader.GetOrdinal然后调用相应的获取的方法来获取值(请注意,它的速度更快调用获取使用顺序的方法比它要使用索引与场的名称)。

然而,这将每次招致序号的查找。如果你通过了多项纪录在一个只进,只读方式迭代(这是的完全的东西DbDataReader实例是为了做),那么你可以的做它减少这种查询的开销一旦的。

.Net Web项目安装包制作一 转

您可以这样做是这样的:

  //移动到第一个记录。如果没有记录,全身而退。
如果回报(dataReader.Read()!);

//循环之前。能做到这一点任何其他领域是
//访问循环中的为好。
INT myFieldNameOrdinal = dataReader.GetOrdinal(MyFieldName);

//过程中的记录。请记住,已经在第一条记录,所以
//用做/而在这里。
做
{
    //做一些与你的领域。
    Console.WriteLine(dataReader.GetString(myFieldNameOrdinal));
}而(dataReader.Read());
 

Using the SqlDataReader class, what, if any, are the functional differences between:

(string) dataReader["MyFieldName"];

and

dataReader.GetString(dataReader.GetOrdinal("MyFieldName"));

解决方案

Casting issues aside, for the singular call, there are none. The indexer will make a call to DbDataReader.GetOrdinal and then call the appropriate Get method to get the value (note that it's faster to call the Get methods using an ordinal than it is to use the indexer with the field name).

However, this will incur a lookup of the ordinal every time. If you are iterating through a number of records in a forward-only, read-only way (which is exactly what DbDataReader instances are meant to do), then you can reduce the overhead of this lookup by doing it just once.

You could do so like this:

// Move to the first record.  If no records, get out.
if (!dataReader.Read()) return;

// Before the loop.  Can do this for any other fields being
// accessed in the loop as well.
int myFieldNameOrdinal = dataReader.GetOrdinal("MyFieldName");

// Process the records.  Remember, already on the first record, so
// use do/while here.
do
{
    // Do something with your field.
    Console.WriteLine(dataReader.GetString(myFieldNameOrdinal));
} while (dataReader.Read());

 
精彩推荐
图片推荐