Re: accessing column types without doing a query by headware
headware
Mon Jul 28 23:29:36 CDT 2003
davidsc@online.microsoft.com (David Sceppa) wrote in message news:<zdPufZTVDHA.2000@cpmsftngxa06.phx.gbl>...
> Each DataReader object exposes a GetSchemaTable method that
> returns a DataTable of schema information about the resultset.
> Each row in the schema table corresponds to a column in the
> resultset. You can use this schema information to get column
> names, data types, etc. The .NET data type (System.String) is
> available in the DataType column and the .NET provider-specific
> data type (OleDbType.VarWChar) is available in the ProviderType
> column, though the data is returned as simply an integer.
>
> You can call Command.ExecuteQuery and ask for schema
> information without actually executing the query by supplying a
> CommandBehavior of SchemaOnly.
>
> Supplying a CommandBehavior of KeyInfo will include
> additional schema information such as base column and table
> names, key column information, etc.
>
> I hope this information proves helpful.
>
> David Sceppa
> Microsoft
> This posting is provided "AS IS" with no warranties,
> and confers no rights. You assume all risk for your use.
> © 2003 Microsoft Corporation. All rights reserved.
The only problem I found with using the
OleDbDataReader.GetSchemaTable() method is that you can't find the
type for a specific field by name like this:
DataTable schemTbl = dataReader.GetSchemaTable();
DataRow row = schemTbl.Rows["age"]; //can't do this
Console.WriteLine(row["DataType"]);
you have to use the integer index of the row since you can't index the
Rows collection with a string, so you end up having to do this:
DataTable schemTbl = dataReader.GetSchemaTable();
DataRow row = schemTbl.Rows[0]; //can't use the column name here
Console.WriteLine(row["DataType"]);
and I really would like to be able to get the field type based on the
field name and not on its index in the table. Fortunately, while
looking into your suggestion, I found that I can get the schema info I
want from the OleDbDataReader object itself by using the
GetFieldType() and GetOrdinal() methods like this:
Console.WriteLine(dr.GetFieldType(dr.GetOrdinal("age")));
It's too bad that they decided to provide so many ways of getting
schema info (through GetSchemaTable(), GetOleDbSchemaTable(), and the
GetFieldType() methods to name a few) because it gets a little
confusing. Let me know if I'm wrong about not being able to use the
field name with the GetSchemaTable() function.
Dave