tags:

views:

144

answers:

3

How can I get a list of fields from OdbcDataReader in C#?

For example, for a table with two fields, Field1 and Field2:

DbCommand.CommandText = "SELECT * FROM TABLE WHERE 0=1";
DbReader = DbCommand.ExecuteReader();

DbReader.??? would give to me a list of two elements - ["Field1","Field2"]

Is there such a function?

A: 

If I understand you correctly, you want the field names from the table—this can be done using the OleDbSchemaGuid class.

Here's a helpful link which walks you through getting table and column names.

And a more in-depth Microsoft article about 'OleDbSchemaGuid'.

Mark B
A: 

You can use OdbcDataReader.GetSchemaTable to get information about the columns for the current result set (I think - the documentation isn't clear about whether or not it supports multiple result sets). You should read the linked documentation if you plan to rely on this method.

In particular, note the following:

The .NET Framework Data Provider for ODBC assumes that metadata information is available from an ODBC driver after one of SQLPrepare, SQLExecute, or SQLExecuteDirect functions are called. For "SchemaOnly" command behavior to work correctly, SQLPrepare must return the required metadata information. Not all ODBC drivers support this function or return metadata information.

And this:

To make sure that metadata columns return the correct information, you must call ExecuteReader with the behavior parameter set to KeyInfo. Otherwise, some of the columns in the schema table may return default, null, or incorrect data.

Jeff Sternal
+1  A: 

I think I know what you may be looking for. If you are asking "Regardless of the query text can you list the field names of the returned dataset without hitting the db for a schema check?" then this should work for you:

var db = new System.Data.Odbc.OdbcConnection ( @"MyODBCSqlConnectionString" );
db.Open();

var cmd = db.CreateCommand();
cmd.CommandText = "SELECT * from MyTable";
var reader = cmd.ExecuteReader();

for( int ordinal = 0; ordinal< reader.FieldCount; ordinal++)
    Console.WriteLine( "Field {0}: {1}", ordinal, reader.GetName( ordinal ) );
Simon Wilson