C# 获取Access数据库中所有表名及其列名、列类型
摘要:
DataTable tables = connnection.GetOleDbSchemaTable( OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataTable schemaTable = connnection.GetOleDbSchemaTable (OleDbSchemaGuid.Columns, new object[] { null, null, tblName, null });
下面贴出代码:
/// <summary> /// 获取Access数据库中指定表的所有列 /// </summary> private List<string> getExcelTableColumn(string tableName) { //获取表名 string tblName = tableName.Trim(); List<string> list = new List<string>(); if (string.IsNullOrEmpty(tblName)) { return list; } // OpenFileDialog of = new OpenFileDialog(); of.Filter = "Access文件(*.mdb)|*.mdb"; if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { string myString = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + of.FileName + ";"; OleDbConnection oconn = new OleDbConnection(myString); oconn.Open(); //获取表中的所有列信息 DataTable schemaTable = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tblName, null }); //获取到列名称 foreach (DataRow row in schemaTable.Rows) { list.Add(row["column_name"].ToString()); } } catch (Exception exc) { //PublicMethod.MessageError("加载Access文件过程发生异常,请重试!"); } } return list; } /// <summary> /// 获取Access数据库中指定表的所有列 /// </summary> /// <param name="con">连库字符串</param> /// <param name="tableName">表名称</param> /// <returns></returns> private List<string> getExcelTableColumn(string con, string tableName) { //获取表名 string tblName = tableName.Trim(); List<string> list = new List<string>(); if (string.IsNullOrEmpty(tblName)) { return list; } // try { OleDbConnection oconn = new OleDbConnection(con); oconn.Open(); //获取表中的所有列信息 DataTable schemaTable = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tblName, null }); //获取到列名称 foreach (DataRow row in schemaTable.Rows) { list.Add(row["column_name"].ToString()); } } catch (Exception exc) { //PublicMethod.MessageError("加载Access文件过程发生异常,请重试!"); } return list; } /// <summary> /// 获取Access数据库中所有表名称 /// </summary> private List<string> getExcelTables() { List<string> list = new List<string>(); OpenFileDialog of = new OpenFileDialog(); of.Filter = "Access文件(*.mdb)|*.mdb"; if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { string conStr = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + of.FileName + ";"; OleDbConnection oconn = new OleDbConnection(conStr); oconn.Open(); //获取库中的所有表信息 DataTable tables = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); foreach (DataRow item in tables.Rows) { list.Add(item["table_name"].ToString()); getExcelTableColumn(conStr,item["table_name"].ToString());//可以在这获取下表的列 } } catch (Exception exc) { //PublicMethod.MessageError("加载Access文件过程发生异常,请重试!"); } } return list; }