使用OLE时如何绕过MS Access启动?

时间:2009-01-13 22:36:04

标签: c# ms-access automation ms-office ole

我正在尝试使用C#和OLE从访问数据库进行自动xml导出。除了显示启动表单外,一切都工作正常,没有用户干预就不会关闭。

这是我到目前为止所做的事情:

objAccess = CreateObject("Access.Application");
objAccess.OpenCurrentDatabase("C:\\MYDB.mdb", true); //true = open in exclusive mode
objAccess.ExportXML(0, "TestTable", "c:\\test.xml");
objAccess.CloseCurrentDatabase();
objAccess.Quit();

2 个答案:

答案 0 :(得分:3)

没有必要打开Access以将表输出到XML,例如,在VBScript中:

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adPersistXML = 1

Dim strCon, cn, rs

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strCon = "Provider= Microsoft.Jet.OLEDB.4.0; Data Source=" & "C:\Docs\LTD.mdb"

cn.Open strCon
rs.Open "Select * from Table1", cn, adOpenStatic, adLockOptimistic

If Not rs.EOF Then
    rs.MoveFirst 
    rs.Save "C:\Docs\Table1.xml", adPersistXML
End If

rs.Close
cn.Close

答案 1 :(得分:0)

据我所知,唯一的方法是在msaccess.exe上使用/ nostartup开关

所以你必须使用shell命令来获取访问对象

我有一个打开数据库并返回对象的函数(这是你必须转换为C#的VBA代码)

Private Function OpenDatabaseWithShell(pDatabaseFullPath As String) As Access.Application

Dim AccObj As Access.Application

    On Error GoTo ErrorHandler

    Set OpenDatabaseWithShell = Nothing

    Dim cmd As String

    On Error Resume Next

    ' basically build full msaccess.exe path and append database name and command switches
    cmd = SysCmd(acSysCmdAccessDir) & "MSAccess.exe """ & psDatabaseFullPath & """"
    cmd = cmd & " /nostartup /excl"

    'start ms access with shell
    Shell PathName:=cmd

    Do 'Wait for shelled process to finish.
      Err = 0
      Set AccObj = GetObject(pDatabaseFullPath)
    Loop While Err <> 0

    On Error GoTo ErrorHandler

    'return access object
    Set OpenDatabaseWithShell = AccObj

NormalExit:
    Exit Function

ErrorHandler:
    'error logging here
    Exit Function

End Function

编辑: 这是一些link到一些类似的VB.NET代码。向下滚动到“创建完整示例Visual Basic .NET项目”并查找“ShellGetDB”函数