Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all tables and all columns from a odbc database

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?

like image 242
GameScripting Avatar asked Aug 30 '12 13:08

GameScripting


1 Answers

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();
like image 110
Fionnuala Avatar answered Sep 28 '22 00:09

Fionnuala