C # dynamically create Access databases and tables,
// Add two com component references // 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"> full path of the database file, for example, 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 a table in the access Database
/// </Summary>
/// <Param name = "filePath"> the full path of the database table file, for example, D :\\ NewDb. mdb, is not found. </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 ();
// Create if the database file does not exist
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 Automatic Growth
// Table. Keys. Append ("FirstTablePrimaryKey", KeyTypeEnum. adKeyPrimary, column, null, null); // defines the 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 );
}
}