用C#代码 怎样获取数据库的所有的表名

2025-03-01 12:25:28
推荐回答(1个)
回答1:

软糖来回答这个问题把。

1.使用Connection的GetSchema方法,参数为"Tables"

        public IList 获取表集合(SqlConnection 连接)
        {
            List 表名 = new List();
            DataTable dt = 连接.GetSchema("Tables");
            foreach (DataRow row in dt.Rows)
            {
                string 表类型 = (string)row["TABLE_TYPE"];
                if (表类型.Contains("TABLE"))
                { 表名.Add(row["TABLE_NAME"].ToString()); }
            }
            return 表名;
        }

2.使用SELECT语句针对系统表进行操作

        public IList 获取表集合2(SqlConnection 连接)
        {
            SqlCommand 命令 = new SqlCommand
            (@"SELECT name FROM sysobjects WHERE (OBJECTPROPERTY(id, N'IsUserTable') = 1)", 连接);
            List 表名 = new List();
            SqlDataReader 读取器 = 命令.ExecuteReader();
            while (读取器.Read())
            {
                string 名称 = 读取器[0].ToString();
                表名.Add(名称);
            }
            读取器.Close();
            return 表名;
        }

以上两种方法都是针对SQL SERVER数据库测试有效,其他的数据库可能需要修改部分代码。


*** 如满意,请采纳,谢谢。 ***