C# 如何獲取SQL Server 中指定數據表的所有字段名和字段類型


接上篇:C# 如何確定SQL Server 中數據表是否存在 ,我們繼續研究SqlConnection.GetSchema 方法,看看如何獲取指定數據表的所有字段名和字段類型。SqlConnection.GetSchema方法有2個重載形式,獲取指定數據表的所有字段名和字段類型的秘密就在GetSchema (String, String[])的第二個參數中。

定義如下:

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

參數collectionName指定要返回的架構的名稱,取值為靜態類 SqlClientMetaDataCollectionNames的成員,如果要取列信息,則取值為SqlClientMetaDataCollectionNames.Columns。

關於SqlClientMetaDataCollectionNames類成員的詳細信息參見:https://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlclientmetadatacollectionnames_fields(v=vs.100).aspx

參數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;
        }
    }
}
View Code

總結:SqlConnection.GetSchema方法用於獲取數據庫架構信息,通過不同參數的組合可實現各種數據架構信息的獲取功能。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM