求助:获取表名
代码写到conn.open()
然后我要获取这个数据库 表的表名,怎么弄?
大侠帮忙
也就是说一个access数据库下有t1、t2、t3 3个表
如何获取表名?
谢谢
[解决办法]
1using System;
2using System.Data;
3using System.Data.OleDb;
4
5namespace Test
6{
7 public class DataOle
8 {
9 /**//// <summary>
10 /// 返回Mdb数据库中所有表表名
11 /// </summary>
12 /// <param name= "strDbPath "> Access数据文件路径 </param>
13 /// <returns> 表名数组 </returns>
14 public static string[] GetShemaTable(string strDbPath)
15 {
16 //创建OleDb数据库连接
17 OleDbConnection pOleConn;
18
19 //设置数据连接
20 pOleConn=new OleDbConnection();
21 pOleConn.ConnectionString=@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " +strDbPath ;
22 pOleConn.Open();
23
24 try
25 {
26 //获取数据表
27 DataTable shemaTable=pOleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null, "TABLE "});
28
29 int n=shemaTable.Rows.Count ;
30 string[] strTable=new string[n];
31 int m=shemaTable.Columns.IndexOf( "TABLE_NAME ");
32
33 for(int i=0;i <n;i++)
34 {
35 DataRow m_DataRow=shemaTable.Rows[i];
36 strTable[i]=m_DataRow.ItemArray.GetValue(m).ToString();
37 }
38
39 return strTable;
40 }
41 catch(OleDbException ex)
42 {
43 Console.WriteLine( "指定的限制集无效! ");
44 Console.WriteLine(ex.Message);
45 return null;
46 }
47 finally
48 {
49 pOleConn.Close();
50 pOleConn.Dispose();
51 }
52 }
53 }
54
55
56 public class AppMain
57 {
58 public static void Main()
59 {
60 string[] TableName=DataOle.GetShemaTable(@ "C:\1.mdb ");
61
62 if(TableName!=null)
63 {
64 //Write each table name
65 for(int i=0;i <TableName.Length;i++)
66 {
67 Console.WriteLine( "DataTale {0} Name is {1} ",i,TableName[i]);
68 }
69 }
70
71 Console.WriteLine( "OK ");
72 }
73 }
74}