Why use the GetOrdinal() Method of the SqlDataReader

白昼怎懂夜的黑 提交于 2019-12-29 05:53:07

问题


What's the difference between reading a value from an SqlDataReader using this syntax:

Dim reader As SqlClient.SqlDataReader
reader("value").ToString()

OR

Dim reader As SqlClient.SqlDataReader
reader.GetString(reader.GetOrdinal("value"))

回答1:


I think that the reason to use GetOrdinal() is so that you can cache the result and re-use it multiple times for performance.

E.g.

Dim reader As SqlClient.SqlDataReader
int valueOrdinal = reader.GetOrdinal("value");
while ( ... )
{
    var value = reader.GetString(valueOrdinal);
}



回答2:


GetOrdinal performs a case-sensitive lookup first. If it fails, a second case-insensitive search is made. GetOrdinal is kana-width insensitive.Because ordinal-based lookups are more efficient than named lookups, it is inefficient to call GetOrdinal within a loop. Save time by calling GetOrdinal once and assigning the results to an integer variable for use within the loop.

Source: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal.aspx




回答3:


I just want to add that the context of how many records you are expecting plays a big role because if you are returning a single row then performance difference between those two would not be significant. However if you are looping over many rows then using typed accessor is better for performance since it's optimized. So in that case if you need to get best performance by using a column name then call GetOrdinal once, put it into a variable and then use typed accessor with the column ordinal in your loop. This would yield the best performance.

if you are curious about the performance difference check out my blog post




回答4:


Your mileage may vary, but...

The more rows you are fetching, the more of a performance improvement you will see. I like to use column aliases in my SELECT statements, like

select
    physical_column_name as "MyFieldName"

and have written a method, should be self-explanatory,

public Dictionary<String, Int32> GetOrdinalsByName(DbDataReader reader)

So, then my assignments look like

    public void BindRow(DbDataReader dr)
    {
        TerminationDate = dr.GetDateTime(_columnOrdinals["TerminationDate"]);

Dictionaries execute close to O(1); so, this is a reasonable tradeoff between performance and maintainability.



来源:https://stackoverflow.com/questions/1079366/why-use-the-getordinal-method-of-the-sqldatareader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!