Add two COM components reference//microsoft ADO Ext. 2.8 for DDL and Security//microsoft ActiveX Data Objects 2.8 Library
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ADOX;
using System.IO;
namespace Webrequesttest.common
{
Public static Class Accessdbhelper
{
// <summary>
/// Create an Access database
// </summary>
// <param name= "FilePath" > The full path of the database file, such as D:\\newdb.mdb</param>
Public static bool Createaccessdb (string filePath)
{
ADOX. Catalog Catalog = new catalog ();
if (! File.exists (FilePath))
{
Try
{
Catalog. Create ("Provider=microsoft.jet.oledb.4.0;ddata source=" + FilePath + "; Jet oledb:engine type=5 ");
}
catch (System.Exception ex)
{
return false;
}
}
return true;
}
// <summary>
/// Create tables in an Access database
// </summary>
/// <param name= "FilePath" > database table file full path such as D:\\newdb.mdb not created </param>
/// <param name= "tableName" > table name </param>
/// <param name= "Colums" >adox. Column Object Array </param>
Public static void Createaccesstable (String filePath, String tableName, params ADOX. Column[] colums)
{
ADOX. Catalog Catalog = new catalog ();
//Database file does not exist then create
if (! File.exists (FilePath))
{
Try
{
Catalog. Create ("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + FilePath + "; Jet oledb:engine type=5 ");
}
catch (System.Exception ex)
{
}
}
ADODB. Connection cn = New ADODB. Connection ();
CN. Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + filePath, NULL, NULL,-1);
Catalog. ActiveConnection = cn;
ADOX. Table table = new ADOX. Table ();
table. Name = TableName;
foreach (var column in colums)
{
table. Columns.Append (column);
}
//column. parentcatalog = Catalog;
//column. properties["AutoIncrement"]. Value = true; Set auto-Grow
//table. Keys.append ("Firsttableprimarykey", keytypeenum.adkeyprimary, column, NULL, NULL); Defining a primary key
Catalog. Tables.append (table);
CN. Close ();
}
//======================================================================================== Call
//adox. column[] columns = {
//New ADOX. Column () {name= "id", type=datatypeenum.adinteger,definedsize=9},
//New ADOX. Column () {name= "col1", type=datatypeenum.adwchar,definedsize=50},
//New ADOX. Column () {name= "col2", type=datatypeenum.adlongvarchar,definedsize=50}
// };
//Accessdbhelper.createaccesstable ("D:\\111.mdb", "testtable", columns);
}
}
C # Dynamic creation of Access databases and tables