Lemuel  Adane Lemuel Adane - 2 months ago 23
C# Question

Check for MS Access database table if not exist create it

How do you programmatically check for MS Access database table, if not exist then create it?

Answer

Simply execute following code if table will exist it will return error other wise it will create a new one:

try
{
        OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + frmMain.strFilePath + "\\ConfigStructure.mdb");
        myConnection.Open();
        OleDbCommand myCommand = new OleDbCommand();
        myCommand.Connection = myConnection;
        myCommand.CommandText = "CREATE TABLE <yourtable name>(<columns>)";
        myCommand.ExecuteNonQuery();
        myCommand.Connection.Close();
}
catch(OleDbException e)
{  
    if(e.ErrorCode == 3010 || e.ErrorCode == 3012)
    // if error then table exist do processing as required
}

Those error codes are returned if a table already exists - check here for all.

Comments