Why use the GetOrdinal() Method of the SqlDataReader

前端 未结 4 1958
北海茫月
北海茫月 2020-12-16 12:55

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

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


        
相关标签:
4条回答
  • 2020-12-16 13:14

    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

    0 讨论(0)
  • 2020-12-16 13:22

    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.

    0 讨论(0)
  • 2020-12-16 13:23

    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

    0 讨论(0)
  • 2020-12-16 13:36

    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);
    }
    
    0 讨论(0)
提交回复
热议问题