1. 程式人生 > >C# 如何獲取SQL Server 中指定資料表的所有欄位名和欄位型別

C# 如何獲取SQL Server 中指定資料表的所有欄位名和欄位型別

如何獲取指定資料表的所有欄位名和欄位型別。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"來實現。

實現程式碼如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data;
 4 using System.Data.SqlClient;
5 6 namespace scratchline.cn 7 { 8 public struct Field 9 { 10 public string Name; 11 public string Type; 12 } 13 14 public class scratchline 15 { 16 public List<Field> GetFileds(string connectionString, string tableName) 17 { 18 List<Field> _Fields = new List<Field>(); 19 SqlConnection _Connection = new SqlConnection(connectionString); 20 try 21 { 22 _Connection.Open(); 23 24 string[] restrictionValues = new string[4]; 25 restrictionValues[0] = null; // Catalog 26 restrictionValues[1] = null; // Owner 27 restrictionValues[2] = tableName; // Table 28 restrictionValues[3] = null; // Column 29 30 using (DataTable dt = _Connection.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictionValues)) 31 { 32 foreach (DataRow dr in dt.Rows) 33 { 34 Field field; 35 field.Name = dr["column_name"].ToString(); 36 field.Type = dr["data_type"].ToString(); 37 _Fields.Add(field); 38 } 39 } 40 } 41 catch (Exception ex) 42 { 43 throw ex; 44 } 45 finally 46 { 47 _Connection.Dispose(); 48 } 49 50 return _Fields; 51 } 52 } 53 }
View Code

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