Friday, April 27, 2018

How to Add a New Table with Primay Key on a Microsoft Access Database File Using C#

Presented below is the code snippet for adding a new table on a Microsoft Access database file. It will also automatically generate a column named ID as the primary key with autoincrementing integer value.


using System.Data.OleDb;

string fileName = "YourDatabaseFilename";
string password = "TheDatabasePassword";
string tableName = "NewTableName";
string connectionString ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" + fileName +
                                           ".accdb; Jet OLEDB:Database Password =" + password + "; Mode=12";

OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
string query = "CREATE TABLE " + tableName+
                         "(ID int identity, " + "CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID))" 
OleDbCommand command = new OleDbCommand(query, con);
command.ExecuteNonQuery();
con.Close();


Pages you may also want to visit:


Creating a Microsoft Access Database File

No comments:

Post a Comment