C# 获取数据库表名、列名
ou.cs 人气:0C# 获取数据库中所有表名、列名,实现代码如下所示:
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; }
加载全部内容