接上篇: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; } } }
總結:SqlConnection.GetSchema方法用於獲取數據庫架構信息,通過不同參數的組合可實現各種數據架構信息的獲取功能。