问题
I have a few MS-Access queries in several *.mdb
files. They are quite complex.
So I just want to open a file, run specific queries which it contains and get a resulting table back.
How can I do that ?
(I know we can just connect via connection string etc. but I want to explore this way.)
My sample code (edited to disable security alerts):
using Microsoft.Office.Interop.Access;
using Microsoft.Office.Core;
var app = new Application();
app.OpenCurrentDatabase(@"C:\test.mdb", true);
app.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityLow;
app.Visible = false;
// run query
app.Quit();
Sample query:
select date(), date()-1
回答1:
To run the query from within an instance of the Microsoft Access application (e.g., to run queries that use custom VBA functions and other features that may not be available to queries from direct System.Data.OleDb or System.Data.Odbc connections) you can do something like this:
var accApp = new Microsoft.Office.Interop.Access.Application();
accApp.OpenCurrentDatabase(@"C:\Users\Public\Database1.accdb");
Microsoft.Office.Interop.Access.Dao.Database cdb = accApp.CurrentDb();
Microsoft.Office.Interop.Access.Dao.Recordset rst =
cdb.OpenRecordset(
"SELECT FullName FROM ClientQuery",
Microsoft.Office.Interop.Access.Dao.RecordsetTypeEnum.dbOpenSnapshot);
while (!rst.EOF)
{
Console.WriteLine(rst.Fields["FullName"].Value);
rst.MoveNext();
}
rst.Close();
accApp.CloseCurrentDatabase();
accApp.Quit();
来源:https://stackoverflow.com/questions/25748939/run-access-queries-via-interop