I found out how to accomplish creating queries in Access using C# so I thought I would post my solution to this in case anyone else ever has a need to do this via C#.
I had to add a reference to DAO.dll version 3.6 (found on my machine in c:\Program Files\Common Files\Microsoft Shared\DAO).
Some of this code is part of my source code generator but I am sure you can follow the code.
/// <summary>
/// This method creates a query for an Access Database Table.
/// </summary> /// /// <returns></returns> public static bool CreateQuery(DataTable dataTable, QueryTypeEnum queryType) { // initial value bool queryCreated = false; // locals string queryName = ""; string queryText = ""; string path = @"D:\RAD Studio\RADStudioClient\DataClassBuilder.mdb";
try { // if the dataTable exists if ((dataTable != null) && (dataTable.HasPrimaryKey)) { // Create DAO Connection, Workspace & Database. dao._DBEngine dbEngine = new dao.DBEngine(); dao.Workspace workSpace = dbEngine.CreateWorkspace("MainWorkspace", "admin", "", dao.WorkspaceTypeEnum.dbUseJet); dao.Database db = workSpace.OpenDatabase(path, false, false, Type.Missing); // Determine the action to take based upon the // queryType. switch(queryType) { case QueryTypeEnum.Delete: // set queryName queryName = dataTable.Name + "_Delete"; queryText = CreateQueryText(dataTable, QueryTypeEnum.Delete); // required break break;
case QueryTypeEnum.FetchAll: // set queryName queryName = dataTable.Name + "_FetchAll"; queryText = CreateQueryText(dataTable, QueryTypeEnum.FetchAll); // required break break; case QueryTypeEnum.Find: // set queryName queryName = dataTable.Name + "_Find"; queryText = CreateQueryText(dataTable, QueryTypeEnum.Find);
// required break break; case QueryTypeEnum.Insert: // set queryName queryName = dataTable.Name + "_Insert"; queryText = CreateQueryText(dataTable, QueryTypeEnum.Insert); // required break break; case QueryTypeEnum.Update:
// set queryName queryName = dataTable.Name + "_Update"; queryText = CreateQueryText(dataTable, QueryTypeEnum.Update);
// required break break; } // Delete Query In Case It Already Exists DeleteQuery(queryName, db); // Create QueryDef QueryDef query = db.CreateQueryDef(queryName, queryText);
// if the query was created if (query != null) { // query was created queryCreated = true; } } } catch(Exception error) {
// Inform User of error MessageBox.Show("An error occurred connecting to the local database." + Environment.NewLine + error.ToString(), "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Information); }
// return value return queryCreated; }