Get all tables and all columns from a odbc database

GameScripting picture GameScripting · Aug 30, 2012 · Viewed 19.6k times · Source

I want to get all "table" names from a OdbcConnection, and for all "table" names I want to recieve all column names.

So I came across the OdbcConnection.GetSchema() functionallity. I manges to get all the table names by simply using connection.GetSchema("Tables"). But now I want to get the column information for those tables. I noticed connection.GetSchema("Columns") will give me columns information, but this only gives it from a random/first (?) "table" in the datasource (using Windows CSV driver), which doesn't help very mutch.

The most challenging part is, that would have to work with any (most) ODBC drivers. I won't know which underlying datasource will be used.

Any ideas?

Answer

Fionnuala picture Fionnuala · Aug 30, 2012

The column schema will return all tables

cn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns,
       new Object[] { null, null, null, null });

Or for a single table

cn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns,
       new Object[] { null, null, "table1", null });

Similarly,

columns = cn.GetSchema("Columns");

Returns all columns in all tables.

More info: Schema Restrictions

Edit re comments

    string cs = @"Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=z:\docs;";
    OdbcConnection cn = new OdbcConnection(cs);
    cn.Open();

    DataTable tables = cn.GetSchema("Tables");
    DataTable columns = cn.GetSchema("Columns");

    foreach (DataRow row in columns.Rows)
    {
        Console.WriteLine(row["COLUMN_NAME"].ToString());
        Console.WriteLine(row["TABLE_NAME"].ToString());
    }
    Console.Read();