博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

获取Access数据里所有表的名称和表的字段

Posted on 2010-08-06 14:16  moss_tan_jun  阅读(493)  评论(0编辑  收藏  举报

--------------
//获取Access数据库表名
        public void GetTableName()
        {
                string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @"C:\信息技术考试成绩.mdb";
                OleDbConnection conn = new OleDbConnection(connString);              

                conn.Open();
                DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                conn.Close();
                int n = dt.Rows.Count;
                string[] tableName = new string[n];
                int m = dt.Columns.IndexOf("TABLE_NAME");
                for (int i = 0; i < n; i++)
                {
                    DataRow dr = dt.Rows[i];
                    tableName[i] = dr.ItemArray.GetValue(m).ToString();

                    this.cbxtable.Items.Add(tableName[i].ToString());
                }
                this.cbxtable.SelectedIndex = 0;

                                                       
          }

 

        /// <summary>
        /// 返回某一表的所有字段名
        /// </summary>
        public List<string> GetTableColumn(string tableName)
        {
            string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @"C:\信息技术考试.mdb";
            OleDbConnection conn = new OleDbConnection(connString);
            List<string> list = new List<string>();
            DataTable dt = new DataTable();
            try
            {
               
                conn.Open();
                dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tableName, null });
                int n = dt.Rows.Count;
                string[] strTable = new string[n];
                int m = dt.Columns.IndexOf("COLUMN_NAME");
                for (int i = 0; i < n; i++)
                {
                    DataRow dr = dt.Rows[i];
                    list.Add(dr.ItemArray.GetValue(m).ToString());
                }
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {

            string str = this.cbxtable.SelectedItem.ToString();
            {
                List<string> lst = GetTableColumn(str);
                listBox1.DataSource = lst;

            }

        }