C#获取SQLServer数据库表名和字段名

SQLServer数据库每个数据库都有INFORMATION_SCHEMA视图,数据库的结构信息Schema都在这里存储。

select TABLE_NAME,TABLE_TYPE,TABLE_CATALOG,TABLE_SCHEMA from INFORMATION_SCHEMA.TABLES;

select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS t where t.TABLE_NAME = 'StoreType';

图一:

C#获取SQLServer数据库表名和字段名

图二:

C#获取SQLServer数据库表名和字段名


C#实现代码如下:(采用Winform窗台编写的)

using System;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace GetTableNameAndFieldName
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            SayHello();
        }
        public void SayHello()
        {
            SqlHelper.connectionString = "Server=LocalHost;DataBase=StdentDB;Uid=Sa;Pwd=123;";

            // 从指定数据库中查找所有表名
            string sqlTableName = "Select * From Information_Schema.Tables";
            StringBuilder tableNames = new StringBuilder();
            using (SqlDataReader dr = SqlHelper.ExecuteReaderByText(sqlTableName, null))
            {
                while (dr.Read())
                {
                    // 表名
                    tableNames.Append(dr["Table_Name"]+",");
                }
            }
            MessageBox.Show("数据库中所有表名:"+tableNames.ToString(),"小赖温馨提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            StringBuilder fieldNames = new StringBuilder();
            // 遍历数据表
            foreach (var tableName in Convert.ToString(tableNames).Split(','))
            {
                // 从指定表名中查找所有字段名
                string sqlFieldName = "Select * From Information_Schema.Columns t Where t.Table_Name = '" + tableName+ "'";
                using (SqlDataReader dr = SqlHelper.ExecuteReaderByText(sqlFieldName, null))
                {         
                    while (dr.Read())
                    {
                        // 字段名
                        fieldNames.Append(dr["Column_Name"] + ",");
                    }
                }   
            }
            MessageBox.Show("所有数据表中的所有字段名:"+fieldNames.ToString(),"小赖温馨提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }
    }
}