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

[sourcecode lang=’csharp’] 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();
}

Post a Comment

Be the First to Comment!

wpDiscuz