C#動態(tài)創(chuàng)建Access數(shù)據(jù)庫

字號:

記得以前要動態(tài)的創(chuàng)建Access數(shù)據(jù)庫的mdb文件都是采用DAO,用VC開發(fā),一大堆的API,很是麻煩?,F(xiàn)在好像也鮮有人提起DAO。其實動態(tài)的創(chuàng)建mdb數(shù)據(jù)的最簡單的方法還是ADOX。
     用ADOX創(chuàng)建access數(shù)據(jù)庫方法很簡單,只需要new一個Catalog對象,然后調用它的Create方法就可以了,如下:
    ADOX.Catalog catalog = new Catalog();
    catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\test.mdb;Jet OLEDB:Engine Type=5");
     僅僅兩行代碼就搞定了。下來我主要介紹一下在c#中的實現(xiàn)細節(jié)。首先你要添加引用,在“Add reference”對話框里切換到Com頁面,選擇“Microsoft ADO Ext. 2.8 for DDL and Security”,然后點擊OK。在文件的開頭using ADOX名字空間。然后添加如上面所示的代碼就可以成功的創(chuàng)建Access 數(shù)據(jù)庫了,代碼如下:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using ADOX;
    namespace testADOX
    ...{
     class Program
     ...{
     static void Main(string[] args)
     ...{
     ADOX.Catalog catalog = new Catalog();
     catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\test.mdb;Jet OLEDB:Engine Type=5");
     }
     }
    }
    創(chuàng)建了數(shù)據(jù)庫文件是沒有實際用處的,我們還要創(chuàng)建表。在創(chuàng)建表之前,我們必須連接目標數(shù)據(jù)庫,用來連接數(shù)據(jù)的橋梁居然是ADO的Connection對象,所以我們不得不再次添加對ADO的應用,在添加引用對話框中切換到Com頁面,選擇“Microsoft ActiveX Data Objects 2.8 Library”,然后點擊OK。下邊是創(chuàng)建表的完整代碼:using System;
    using System.Collections.Generic;
    using System.Text;
    using ADOX;
    namespace testADOX
    ...{
     class Program
     ...{
     static void Main(string[] args)
     ...{
     ADOX.Catalog catalog = new Catalog();
     catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\test.mdb;Jet OLEDB:Engine Type=5");
     ADODB.Connection cn = new ADODB.Connection();
     cn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\test.mdb", null, null, -1);
     catalog.ActiveConnection = cn;
     ADOX.Table table = new ADOX.Table();
     table.Name = "FirstTable";
     ADOX.Column column = new ADOX.Column();
     column.ParentCatalog = catalog;
     column.Name = "RecordId";
     column.Type = DataTypeEnum.adInteger;
     column.DefinedSize = 9;
     column.Properties["AutoIncrement"].Value = true;
     table.Columns.Append(column, DataTypeEnum.adInteger, 9);
     table.Keys.Append("FirstTablePrimaryKey", KeyTypeEnum.adKeyPrimary, column, null, null);
     table.Columns.Append("CustomerName", DataTypeEnum.adVarWChar, 50);
     table.Columns.Append("Age", DataTypeEnum.adInteger, 9);
     table.Columns.Append("Birthday", DataTypeEnum.adDate, 0);
     catalog.Tables.Append(table);
     cn.Close();
     }
     }
    }
    上面的代碼中,創(chuàng)建了一個名為FirstTable的表,在表里加入了4個字段,并設置了一個主鍵。表里的字段分別輸入4中不同的常用類型,第一個字段是一個自動增長的整數(shù)類型,這個類型比較特殊,你必須為這個字段設置ParentCatalog屬性,并將“AutoIncrement”的屬性值設為true.。Access里的Text類型對應的就是adVarWchar,而日期類型對應的是adDate。
    鍵的設置如table.Keys.Append("FirstTablePrimaryKey", KeyTypeEnum.adKeyPrimary, column, null, null)所示,如果是外鍵的話,你還必須要設置關聯(lián)的表和關聯(lián)的字段,也就是Append方法的后兩個字段。