ASP.NET 取得SQLSERVER数据库中所有表,所有字段,所有字段类型

// ==================
// WebForm1.cs
// 时间:2006-8-29 15:44
// 作者:龚韬
// 目的:取出指定数据库里所有用户表,表里所有字段和字段的数据类型
// EMail: gy3z@163.com
// ==================

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Data.SqlClient; 


namespace Persistence

 
public class WebForm1 : System.Web.UI.Page
 
{
  
private string CONN_STR = "packet size=4096;user id=sa;data source=.;persist security info=True;initial catalog=RichSpace;password=这里是密码";
  
  
private ArrayList TablesName= new ArrayList();
  
private ArrayList al = new ArrayList();

  
private void Page_Load(object sender, System.EventArgs e)
  

   ListTableDetail();
  }


  
// 列出所有表,表里的所有字段和数据类型
  private void ListTableDetail()
  
{
   
// 取得所有表名
   GetTablesName();

   
// 初始化所有表字段及类型。
   for(int i=0; i<this.TablesName.Count;i++)
   

    GetTableFields(TablesName[i].ToString());
   }


   
// 将结果打印出来
   for(int i=0; i<this.TablesName.Count;i++)
   

    ArrayList str 
= (ArrayList)al[i];

    Response.Write(
"<ul>");
    Response.Write(
"<li><strong>"+TablesName[i].ToString()+"</strong></li>");
    
for(int j=0; j<str.Count; j++)
    
{  
     Response.Write(
"<br/>"+str[j].ToString()+"");
    }

    Response.Write(
"</ul>");
   }

  
  }


  
// 取得所有表名,存放在 TablesName 数组里
  private void GetTablesName()
  
{
   SqlConnection conn 
= new SqlConnection(CONN_STR);
   
   SqlCommand cmd 
= new SqlCommand();
   cmd.Connection  
= conn;
   cmd.CommandType 
= CommandType.Text;

   
// "Select name From Sysobjects where type='u'" 取得用户表名。
   cmd.CommandText = "Select name From Sysobjects where type='u'";
   conn.Open();

   SqlDataReader sdr 
= cmd.ExecuteReader();
   
while(sdr.Read())
   
{
    
this.TablesName.Add(sdr[0].ToString());
   }


   sdr.Close();
   conn.Close();
  }


  
// 取得表的所有字段及数据类型,以ArrayList数组,加入到al数据里
  private void GetTableFields(string TableName)
  
{
   SqlConnection conn 
= new SqlConnection(CONN_STR);
   
   SqlCommand cmd 
= new SqlCommand();
   cmd.Connection  
= conn;
   cmd.CommandType 
= CommandType.Text;
   cmd.CommandText 
= "Select top 1 * From "+TableName;
   conn.Open();
  
   
   SqlDataAdapter sda 
= new SqlDataAdapter(cmd); 

   DataTable dt 
= new DataTable(TableName) ;
   sda.Fill(dt);
   
   ArrayList str
=new ArrayList();
 
   
for(int i=0; i<dt.Columns.Count; i++)
   

    
// dt.Columns[i].ColumnName 是字段名,dt.Columns[i].DataType.ToString() 字段类型
    str.Add(dt.Columns[i].ColumnName+" ["+dt.Columns[i].DataType.ToString()+"]");
   }
 
   al.Add(str);
   dt.Clear();
   conn.Close();
  }

  
Web 窗体设计器生成的代码
 }

}



posted on 2006-09-01 18:44  Ameng  阅读(590)  评论(0)    收藏  举报