0

A Microsoft Office Access database contains Tables, Queries, Forms and Reports.

Is it possible to build and save a query in the Access database from C#?

For example, I know I can use OLEDB to connect to an Access database and use SQL commands using its tables and already defined queries, but how would I build a new query and then save it in the database?

3
  • I see multiple examples of how to query access or display data on a data table but not actually create a query from scratch and save it in an access database. Hence why I posted my question. Commented Apr 15, 2014 at 19:41
  • I am going to give you one hint .. look at how to use OleDB or SqlClient library Commented Apr 15, 2014 at 19:55
  • 1
    All results I have seen that use OleDB or SqlClient library just return the results to a dataset. I have yet to see an example that shows you how to save the SQL string as an access query. Commented Apr 15, 2014 at 19:59

1 Answer 1

3

If you want to add Querydefinitons to an existing access database you can do so with the Access Interop asssembly.

Create a new c# project and add a reference to:

Microsoft Office 12.0 Access database engine Object Library

(or a version that matches your Office/Access version)

This code creates a Query in the Access Database for every table in the database to query the count of rows:

        var dbe = new DBEngine();
        var db = dbe.OpenDatabase(@"c:\path\to\your\youraccessdatabase.accdb");

        // loop over tables
        foreach (TableDef t in db.TableDefs)
        {
            // create a querydef
            var qd = new QueryDef();
            qd.Name = String.Format("Count for {0}", t.Name);
            qd.SQL = String.Format("SELECT count(*) FROM {0}", t.Name);

            //append the querydef (it will be parsed!)
            // might throw if sql is incorrect
            db.QueryDefs.Append(qd);
        }

        db.Close();
Sign up to request clarification or add additional context in comments.

1 Comment

Here I am close to a year later and still enjoying this solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.