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"))
GetOrdinal performs a case-sensitive lookup first. If it fails, a second, case-insensitive search occurs (a case-insensitive comparison is done using the database collation). Unexpected results can occur when comparisons are affected by culture-specific casing rules.
To create a SqlDataReader, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor. While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it.
SqlDataReader objects allow you to read data in a fast forward-only manner. You obtain data by reading each row from the data stream. Call the Close method of the SqlDataReader to ensure there are not any resource leaks.
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With