// ==================
// 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();
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}