如何获取MS Access数据库表的字段名称?
我可以使用SQL查询,还是有C#代码来执行此操作?
使用IDataReader.GetSchemaTable()
这是一个访问表模式并以XML格式打印它的实际示例(只是为了查看您获得的信息):
class AccessTableSchemaTest { public static DbConnection GetConnection() { return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\Test.mdb"); } static void Main(string[] args) { using (DbConnection conn = GetConnection()) { conn.Open(); DbCommand command = conn.CreateCommand(); // (1) we're not interested in any data command.CommandText = "select * from Test where 1 = 0"; command.CommandType = CommandType.Text; DbDataReader reader = command.ExecuteReader(); // (2) get the schema of the result set DataTable schemaTable = reader.GetSchemaTable(); conn.Close(); } PrintSchemaPlain(schemaTable); Console.WriteLine(new string('-', 80)); PrintSchemaAsXml(schemaTable); Console.Read(); } private static void PrintSchemaPlain(DataTable schemaTable) { foreach (DataRow row in schemaTable.Rows) { Console.WriteLine("{0}, {1}, {2}", row.Field("ColumnName"), row.Field ("DataType"), row.Field ("ColumnSize")); } } private static void PrintSchemaAsXml(DataTable schemaTable) { StringWriter stringWriter = new StringWriter(); schemaTable.WriteXml(stringWriter); Console.WriteLine(stringWriter.ToString()); } }
兴趣点:
不要通过给出总是求值为false的where子句来返回任何数据.当然,只有当您对数据不感兴趣时才适用:-).
使用IDataReader.GetSchemaTable()获取DataTable,其中包含有关实际表的详细信息.
对于我的测试表,输出是:
ID, System.Int32, 4 Field1, System.String, 50 Field2, System.Int32, 4 Field3, System.DateTime, 8 --------------------------------------------------------------------------------[...] ID 0 4 10 255 System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 3 false true false false false false false
这将适用于sql server 2005及以上版本:
select * from INFORMATION_SCHEMA.COLUMNS where TABLE_Name='YourTableName' order by ORDINAL_POSITION