Get all tables and all columns from a odbc database

我与影子孤独终老i 提交于 2019-12-09 12:15:27

问题


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?


回答1:


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();



回答2:


I know it's too late to help the original poster but if it helps anyone else I made a mini project that goes through all the ODBC Tables and creates a class for each one with the column names as string fields. You can use these classes to compose string queries.

Link to project



来源:https://stackoverflow.com/questions/12197532/get-all-tables-and-all-columns-from-a-odbc-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!