Run Access Queries via Interop?

大城市里の小女人 提交于 2019-12-11 06:56:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!