Get Table Schema Programatically

August 18th, 2006 Leave a comment Go to comments

In order to retreive table schema programatically, we can use the GetSchemaTable method of the DataReader as follows:

using (OleDbConnection cn = new OleDbConnection())
{
    OleDbCommand cmd;
    DataTable schemaTable;
    OleDbDataReader reader;

    cn.ConnectionString = @"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Northwind;Data Source=(local);";
    cn.Open();

    cmd = new OleDbCommand("Employees", cn);
    cmd.CommandType = CommandType.TableDirect;

    using (reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo))
    {
        schemaTable = reader.GetSchemaTable();

        foreach (DataRow row in schemaTable.Rows)
        {
            foreach (DataColumn col in schemaTable.Columns)
                Console.WriteLine(col.ColumnName + " = " + row[col].ToString());

            Console.WriteLine();
        }

        reader.Close();
    }

    cn.Close();
}

  1. No comments yet.
  1. No trackbacks yet.
 

Comment moderation is enabled. Your comment may take some time to appear.