C# 如何获取SQL Server | SQLite中指定数据表的所有字段名和字段类型

我们继续研究SqlConnection.GetSchema 方法,
看看如何获取指定数据表的所有字段名和字段类型
SqlConnection.GetSchema方法有2个重载形式,
获取指定数据表的所有字段名和字段类型的秘密就在
GetSchema (String, String[])的第二个参数中。

public override DataTable GetSchema(
    string collectionName,
    string[] restrictionValues
)

参数collectionName指定要返回的架构的名称,取值为静态类 SqlClientMetaDataCollectionNames的成员,
如果要取列信息,则取值为SqlClientMetaDataCollectionNames.Columns。

关于SqlClientMetaDataCollectionNames类成员的详细信息参见

https://docs.microsoft.com/zh-cn/dotnet/api/system.data.sqlclient.sqlclientmetadatacollectionnames?redirectedfrom=MSDN&view=dotnet-plat-ext-3.1#fields

参数restrictionValues为请求架构的一组限制值,对于不同的架构集类型,有不同的写法。要具体了解,可以调用GetSchema(“Restrictions”) 方法。

针对SQL Server 数据库,restrictionValues的长度为4,其中
restrictionValues[0]为Catalog(数据库名),
restrictionValues[1]为Owner(所有者),
restrictionValues[2]为Table(表名),
restrictionValues[3]为Column(列名)。

我们要查询某张表中的列名等信息,则可以通过设置restrictionValues[2]=”SomeTableName”来实现。

实现代码如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace scratchline.cn
{
    public struct Field
    {
        public string Name;
        public string Type;
    }

    public class scratchline
    {
        public List<Field>GetFileds(string connectionString, string tableName)
        {
            List<Field> _Fields = new List<Field>();
            SqlConnection _Connection = new SqlConnection(connectionString);
            try
            {
                _Connection.Open();

                string[] restrictionValues = new string[4];
                restrictionValues[0] = null; // Catalog
                restrictionValues[1] = null; // Owner
                restrictionValues[2] = tableName; // Table
                restrictionValues[3] = null; // Column

                using (DataTable dt = _Connection.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictionValues))
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        Field field;
                        field.Name = dr["column_name"].ToString();
                        field.Type = dr["data_type"].ToString();
                        _Fields.Add(field);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _Connection.Dispose();
            }

            return _Fields;
        }
    }
}

总结:SqlConnection.GetSchema方法用于获取数据库架构信息,通过不同参数的组合可实现各种数据架构信息的获取功能。

https://www.cnblogs.com/two/p/5224656.html

https://www.cnblogs.com/GmrBrian/p/6214756.html