如何獲取指定數據表的所有字段名和字段類型。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 }
總結:SqlConnection.GetSchema方法用於獲取數據庫架構信息,通過不同參數的組合可實現各種數據架構信息的獲取功能。
