.NET SqlDataReader的项目[]对的GetString(GetOrdinal())? [英] .NET SqlDataReader Item[] vs. GetString(GetOrdinal())?

查看:89
本文介绍了.NET SqlDataReader的项目[]对的GetString(GetOrdinal())?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 (串)的DataReader [MyFieldName];
 

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

解决方案

铸造问题放在一边,为单一的呼叫,有没有。索引器会打电话到<一个href="http://msdn.microsoft.com/en-us/library/system.data.common.dbdatareader.getordinal.aspx"><$c$c>DbDataReader.GetOrdinal然后调用相应的获取的方法来获取值(请注意,它的速度更快调用获取使用顺序的方法比它要使用索引与场的名称)。

然而,这将每次招致序号的查找。如果你通过了多项纪录在一个只进,只读方式迭代(这是的完全的东西<一个href="http://msdn.microsoft.com/en-us/library/system.data.common.dbdatareader.aspx"><$c$c>DbDataReader实例是为了做),那么你可以的做它减少这种查询的开销一旦的。

您可以这样做是这样的:

  //移动到第一个记录。如果没有记录,全身而退。
如果回报(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());

这篇关于.NET SqlDataReader的项目[]对的GetString(GetOrdinal())?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆