1

I am automating Microsoft Access from C# like so:

using Microsoft.Office.Interop.Access;

static void Main(string[] args)
{
    Application ap = new Application();

    ap.OpenCurrentDatabase("C:\\location.accdb", true);
    ap.DoCmd.WhateverIFeelLike();
    ap.CloseCurrentDatabase();
}

What I want to do here is run one of the select queries stored within Access and return this value either as a string or string array.

I want something like this:

string[] myQueryResult = ap.DoCmd.OpenQuery("qryFoo");

Obviously this doesn't work but this the kind of thing that I am looking for. As a workaround I am thinking of exporting the query results to a CSV file then using Filehelpers to import this into an Array in C# but I thought I would ask on here first in the hope that there is a more direct route!

Thanks

1

1 Answer 1

2

A possibility is to use OleDb. You need to build your project with "x86" as platform target on 64-bit machines, since the Jet drivers are 32-bit.

const string DatabasePath = @"C:\DbPath\MyDatabase.mdb";
const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                                DatabasePath;

using (OleDbConnection cnn = new OleDbConnection(ConnectionString)) {
    string query = "SELECT * FROM qryFoo";
    using (OleDbCommand cmd = new OleDbCommand(query, cnn)) {
        cnn.Open();
        using (OleDbDataReader reader = cmd.ExecuteReader()) {
            int employeeIdOrdinal = reader.GetOrdinal("EmployeeID");
            int nameOrdinal = reader.GetOrdinal("Name");
            int salaryOrdinal = reader.GetOrdinal("Salary");
            while (reader.Read()) {
                Console.WriteLine("EmployeeID = {0}", reader.GetInt32(employeeIdOrdinal));
                Console.WriteLine("Name = {0}", reader.GetString(nameOrdinal));
                if (!reader.IsDBNull(salaryOrdinal)) {
                    Console.WriteLine("Salary = {0}", reader.GetDouble(salaryOrdinal));
                }
                Console.WriteLine("---------------");
            }
        }
    }
}

You do not need Access interop for this to work, however a using System.Data.OleDb;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.