首先引用msadox.dll和msjro.dll(C:\Program Files\Common Files\System\ado\),msjro.dll可以從網上下載下傳,然後引用
[csharp] view plain copy
- using ADOX;
- using JRO;
- using System.IO;
然後編寫相關函數
[csharp] view plain copy
- /// <summary>
- /// 建立資料庫
- /// </summary>
- /// <param name="mdbPath">路徑</param>
- public void Create(string mdbPath)
- {
- if (File.Exists(mdbPath)) //檢查資料庫是否已存在
- {
- throw new Exception("目标資料庫已存在,無法建立");
- }
- // 可以加上密碼,這樣建立後的資料庫必須輸入密碼後才能打開
- mdbPath = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath;
- // 建立一個CatalogClass對象的執行個體,
- ADOX.CatalogClass cat = new ADOX.CatalogClass();
- // 使用CatalogClass對象的Create方法建立ACCESS資料庫
- cat.Create(mdbPath);
- //建立資料庫後關閉連接配接
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection);
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat);
- }
- /// <summary>
- /// 連接配接資料庫
- /// </summary>
- /// <param name="filename">檔案名包含路徑</param>
- /// <returns>傳回連接配接字元串</returns>
- public ADODB.Connection Connection(string filename)
- {
- ADODB.Connection con = new ADODB.Connection();
- con.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filename, null, null, -1);
- return con;
- }
- /// <summary>
- /// 建立資料表
- /// </summary>
- /// <param name="con">連接配接字元串</param>
- /// <param name="table_name">表的名稱</param>
- /// <param name="column">字段</param>
- public void CreateTable(ADODB.Connection con,string table_name,params Column[] column)
- {
- CatalogClass cat = new CatalogClass();
- cat.ActiveConnection = con;
- Table table = new Table();
- Column col = new Column();
- col.ParentCatalog = cat;
- col.Type = DataTypeEnum.adInteger;
- col.Name = "ID";
- col.DefinedSize = 9;
- col.Properties["AutoIncrement"].Value = true;
- table.Columns.Append(col, DataTypeEnum.adInteger, 9);
- table.Keys.Append("FirstPrimaryKey",KeyTypeEnum.adKeyPrimary,col, null, null);
- table.Name = table_name;
- foreach (Column item in column)
- {
- table.Columns.Append(item);
- }
- cat.Tables.Append(table);
- //建立資料庫後關閉連接配接
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection);
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat);
- }
示例:
[csharp] view plain copy
- private void button1_Click(object sender, EventArgs e)
- {
- Create(Path.Combine(Application.StartupPath, "test.mdb"));
- Column col=new Column();
- col.Name="Name";
- col.Type=DataTypeEnum.adVarWChar;
- col.DefinedSize=50;
- CreateTable(Connection(Path.Combine(Application.StartupPath, "test.mdb")),"testtable", col);
- }
轉載于:https://www.cnblogs.com/netuml/articles/3261306.html