日期:2014-05-17  浏览次数:20575 次

ASP.NET通过按钮连接ACCESS数据库并读出该数据库中的表名
一个按钮,一个textBox控件,一个listBox控件,想通过在textbox控件中输入一个ACCESS数据库的路径,通过单击按钮连接数据库,然后在LISTBOX控件中显示该数据库的所有表名,求高手帮助

------解决方案--------------------
探讨

GetOleDbSchemaTable

------解决方案--------------------
C# code

/// <summary>
    /// 取所有表名
    /// </summary>
    /// <returns></returns>
    public List<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 in dt.Rows)
            {
                if (row[3].ToString() == "TABLE")
                    list.Add(row[2].ToString());
            }
            return list;
        }
        catch (Exception e)
        { throw e; }
        finally { if (Conn.State == ConnectionState.Open) Conn.Close(); Conn.Dispose(); }
    }
 
    /// <summary>
    /// 取指定表所有字段名称
    /// </summary>
    /// <returns></returns>
    public List<string> GetTableFieldNameList(string TableName)
    {
        List<string> list = new List<string>();
        OleDbConnection Conn = new OleDbConnection(ConnStr);
        try
        {
            if (Conn.State == ConnectionState.Closed)
                Conn.Open();
            using (OleDbCommand cmd = new OleDbCommand())
            {
                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));
                }
            }
            return list;
        }
        catch (Exception e)
        { throw e; }
        finally
        {
            if (Conn.State == ConnectionState.Open)
                Conn.Close();
            Conn.Dispose();
        }
    }