摘要:讀取Access的程式庫
寫了一個用來讀取Access檔案內容的程式庫,
會把檔案內所有的資料表與檢視表放進指定的DataSet內,
第一個DataTable(名稱為Tables)為資料庫內的資料表列表。
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;
using System.Diagnostics;
namespace WindowsApplication1
{
class ReadAccessFile
{
const String sAccessConnection = @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data source= ";
OleDbConnection odcConnection;
DataTable schemaData;
public void GetAllData(DataSet allData, String accessFile)
{
odcConnection = new OleDbConnection(sAccessConnection + accessFile);
try
{
odcConnection.Open();
schemaData = odcConnection.GetSchema("tables");
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
finally
{
odcConnection.Close();
}
if (schemaData == null)
return;
allData.Tables.Add(schemaData);
foreach (DataRow dr in schemaData.Rows)
{
if (dr["TABLE_TYPE"].ToString() == "VIEW" || dr["TABLE_TYPE"].ToString() == "TABLE")
{
String tableName = String.Format("{0}", dr["TABLE_NAME"]);
DataTable dt = new DataTable(tableName);
ReadTable(dt, accessFile, tableName);
allData.Tables.Add(dt);
}
}
}
void ReadTable(DataTable dt, string fileName, string tableName)
{
try
{
odcConnection.Open();
OleDbCommand odCommand = odcConnection.CreateCommand();
odCommand.CommandText = String.Format("select * from [{0}]", tableName);
OleDbDataReader odrReader = odCommand.ExecuteReader();
dt.Load(odrReader);
odrReader.Close();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
finally
{
odcConnection.Close();
}
}
}
}
用來測試程式庫的程式,只要開一個Windosws的應用程式專案,不用加控制項,在Form1_Load裡面加上這些:
const String accessFile = @"XXX.mdb";
DataSet allData = new DataSet();
ReadAccessFile raf = new ReadAccessFile();
raf.GetAllData(allData, accessFile);
TabControl tabControl = new TabControl();
tabControl.Dock = DockStyle.Fill;
this.Controls.Add(tabControl);
foreach (DataTable dt in allData.Tables)
{
TabPage tp = new TabPage(dt.TableName);
tabControl.Controls.Add(tp);
DataGrid dg = new DataGrid();
tp.Controls.Add(dg);
dg.DataSource = dt;
dg.Dock = DockStyle.Fill;
}
把 XXX.mdb 改為包含完整路徑的Access檔案就可以跑了,會用分頁的方式將所有Access檔案裡的 資料表、檢視表用不同的分頁顯示出來。