Search This Blog

Wednesday, March 12, 2014

How to Retrieve Database Metadata using in .NET using C#

Retrieve metadata associated with any database

Here is sample code given to access metadata information associated with database. 

I used a windows forms listbox control to show the metadata information. On form's Shown event 
the code is written to show the information in list box, Here for sample code is for
display the tables and columns.
Here ms access 2007 northwind sample database file is used.



Code behind:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace MetaDataInfo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            _connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\northwind.accdb;Persist Security Info=False;";
            _connection.Open();
        }
        OleDbConnection _connection = new OleDbConnection();

        private void Form1_Load(object sender, EventArgs e)
        {
           
            //_connection.Open();
            
        }

        public void RetrieveTableInformation()
        {

            DataTable tables = this._connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            foreach (DataRow row in tables.Rows)
            {
                lstTables.Items.Add(row["TABLE_NAME"]);
            }
        }

        public void RetrieveColumnInformation()
        {
            DataTable tables = this._connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null);
            
            foreach (DataRow row in tables.Rows)
            {
                lstColumns.Items.Add (row["TABLE_NAME"] + " : " + row["COLUMN_NAME"]);
            }
        }

       

        private void Form1_Shown(object sender, EventArgs e)
        {
            RetrieveTableInformation();
            RetrieveColumnInformation();
        }

      
    }
}



No comments:

Post a Comment