C# 獲取數據庫中所有表名、列名的示例代碼
C# 獲取數據庫中所有表名、列名,實現代碼如下所示:
List<Dictionary<string, string>> GetColsName(Guid gtype,string tableName,string itemIndex= "COLUMN_NAME") { DataTable dsTablesData = DbDataHelper.GetCon().GetOleDbSchemaTable(gtype, new Object[] { null, null, tableName, null }); List<Dictionary<string, string>> ditCol = new List<Dictionary<string, string>>() ; for (int i = 0; i < dsTablesData.DefaultView.Table.Rows.Count; i++) { ditCol.Add(new Dictionary<string, string> { { i.ToString(), i.ToString() } }); } foreach (DataRow item in dsTablesData.DefaultView.Table.Rows) { int pos = Convert.ToInt32(item["ORDINAL_POSITION"]); int typeIndex = Convert.ToInt32(item["DATA_TYPE"]); ditCol[pos-1]= new Dictionary<string, string> { { item[itemIndex].ToString(), DBData.getInstance().GetColNameType(typeIndex) } }; } return ditCol; } List<string> GetTablesName(Guid gtype,string tableType ="TABLE", string strTableName =null , string itemIndex= "TABLE_NAME") { List<string> strNames = new List<string>(); DataTable dsTablesData = DbDataHelper.GetCon().GetOleDbSchemaTable(gtype, new Object[] { null, null, strTableName, tableType }); foreach (DataRow item in dsTablesData.DefaultView.Table.Rows) { strNames.Add(item[itemIndex].ToString()); } return strNames; }
調用
DBData.getInstance()._tableNames = GetTablesName(OleDbSchemaGuid.Tables); foreach (var tableName in DBData.getInstance()._tableNames) { List<Dictionary<string, string>> tmp = GetColsName(OleDbSchemaGuid.Columns, tableName); }
通過dataTable獲取
/// <summary> /// 根據datatable獲得列名 /// </summary> /// <param name="dt">表對象</param> /// <returns>返回結果的數據列數組</returns> public static List<string> GetColumnsByDataTable(DataTable dt) { List<string> list = new List<string>(); foreach (DataColumn item in dt.Columns) { list.Add(item.ColumnName); } return list; }
到此這篇關於C# 獲取數據庫中所有表名、列名的文章就介紹到這瞭,更多相關C# 獲取數據庫表名、列名內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- C# 遍歷datatable字段名和value的案例
- C# Datatable的幾種用法小結
- C# 減少嵌套循環的兩種方法
- C#去除DataTable重復數據的三種方法
- C# DataTable數據遍歷優化詳解