c# 获取access所有表名 获取指定表所有字段名

来源:互联网 发布:mac画平面图的软件 编辑:程序博客网 时间:2024/05/02 00:53
http://www.cnblogs.com/swtseaman/archive/2011/08/20/2147150.html

/// <summary>
    /// 取所有表名
    /// </summary>
    /// <returns></returns>
    publicList<string> GetTableNameList()
    
        List<string> list =new List<string>();
        OleDbConnection Conn =new OleDbConnection(ConnStr);
        try
        {
            if(Conn.State == ConnectionState.Closed)
                Conn.Open();
            DataTable dt = Conn.GetSchema("Tables");
            foreach(DataRow row indt.Rows)
            {
                if(row[3].ToString() == "TABLE")
                    list.Add(row[2].ToString());
            }
            returnlist;
        }
        catch(Exception e)
        {throw e; }
        finally{ if (Conn.State == ConnectionState.Open) Conn.Close(); Conn.Dispose(); }
    }
 
    /// <summary>
    /// 取指定表所有字段名称
    /// </summary>
    /// <returns></returns>
    publicList<string> GetTableFieldNameList(stringTableName)
    {
        List<string> list =new List<string>();
        OleDbConnection Conn =new OleDbConnection(ConnStr);
        try
        {
            if(Conn.State == ConnectionState.Closed)
                Conn.Open();
            using(OleDbCommand cmd = newOleDbCommand())
            {
                cmd.CommandText ="SELECT TOP 1 * FROM [" + TableName + "]";
                cmd.Connection = Conn;
                OleDbDataReader dr = cmd.ExecuteReader();
                for(int i = 0; i < dr.FieldCount; i++)
                {
                    list.Add(dr.GetName(i));
                }
            }
            returnlist;
        }
        catch(Exception e)
        {throw e; }
        finally
        {
            if(Conn.State == ConnectionState.Open)
                Conn.Close();
            Conn.Dispose();
        }
    }
原创粉丝点击