C method for dynamically creating Access databases and tables
- 2020-12-13 19:03:19
- OfStack
This article illustrates the C# approach to dynamically creating Access databases and tables. Share to everybody for everybody reference.
Specific implementation methods are as follows:
// Add two com A component 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 access The database
/// </summary>
/// <param name="filePath"> Full path to 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>
/// in access Create tables in the database
/// </summary>
/// <param name="filePath"> Full path of database table file such as D:\\NewDb.mdb Create without </param>
/// <param name="tableName"> The name of the table </param>
/// <param name="colums">ADOX.Column An array of objects </param>
public static void CreateAccessTable(string filePath, string tableName, params ADOX.Column[] colums)
{
ADOX.Catalog catalog = new Catalog();
// A database file is created when it 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); // Define 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);
}
}
Hopefully this article has helped you with your C# programming.