Database Reference
In-Depth Information
Replace the ordinal indexers in OrdinalIndexer.cs with column name indexers, and rerun the
project; you'll get the same results as in Figure 14-2. The next section discusses a better approach for
most cases.
Using Typed Accessor Methods
When a data reader returns a value from a data source, the resulting value is retrieved and stored locally
in a .NET type rather than the original data source type. This in-place type conversion feature is a trade-
off between consistency and speed, so to give some control over the data being retrieved, the data reader
exposes typed accessor methods that you can use if you know the specific type of the value being
returned.
Typed accessor methods all begin with Get , take an ordinal index for data retrieval, and are type
safe; C# won't allow you to get away with unsafe casts. These methods turn out to be faster than both the
ordinal and the column name indexer methods. Being faster than column name indexing seems only
logical, because the typed accessor methods take ordinals for referencing; however, we need to explain
how it's faster than ordinal indexing. This is because even though both techniques take in a column
number, the conventional ordinal indexing method needs to look up the data source data type of the
result and then go through a type conversion. This overhead of looking up the schema is avoided with
typed accessors.
.NET types and typed accessor methods are available for almost all data types supported by SQL
Server and OLE DB databases.
Table 14-1 should give you a brief idea of when to use typed accessors and with what data type. It
lists SQL Server data types, their corresponding .NET types, .NET typed accessors, and special SQL
Server-specific typed accessors designed particularly for returning objects of type
System.Data.SqlTypes .
Table 14-1. SQL Server Typed Accessors
SQL Server Data Types
.NET Type
.NET Typed Accessor
bigint
Int64
Getlnt64
binary
Byte[]
GetBytes
bit
Boolean
GetBoolean
char
String or Char[]
GetString or GetChars
datetime
DateTime
GetDateTime
decimal
Decimal
GetDecimal
float
Double
GetDouble
image or long varbinary
Byte[]
GetBytes
int
Int32
Getlnt32
 
Search WWH ::




Custom Search