1

我正在旧 XP 机器上创建一个 32 位应用程序,该应用程序也将在 Win7 或更高版本上运行。

所以我试图测试什么连接字符串可以工作。如:

Private Function test_ace_or_jet(ByVal mdb_path As String) As String
        Dim connString As String
        Dim dbMaintPort As OleDb.OleDbConnection

        connString = ""

        Try
            connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & mdb_path

            dbMaintPort = New OleDb.OleDbConnection(connString)
            dbMaintPort.Open()

            dbMaintPort.Close()

            MsgBox("1 was found")
        Catch ex As Exception
            MsgBox("Could not open 1" & vbCrLf & vbCrLf & ex.Message)
            Try
                connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mdb_path
                dbMaintPort = New OleDb.OleDbConnection(connString)
                dbMaintPort.Open()
                dbMaintPort.Close()

                MsgBox("2 was found")
            Catch ex2 As Exception
                connString = ""
                MsgBox("Could not open 2" & vbCrLf & vbCrLf & ex2.Message)
            End Try
        End Try
        test_ace_or_jet = connString
    End Function

但是我发现的问题是在 XP 机器上,第一个连接字符串不会失败。它根本没有安装 ACE。

如何测试是否使用其中一种?我能否获得上述函数来给我正确的连接字符串?

4

1 回答 1

1

如果你一直在尝试/捕捉直到找到一些东西,你可能会把自己嵌套得很深......你可能会更好(在测试时),做一个循环并有一个连接字符串数组,比如

Private Function test_ace_or_jet(ByVal mdb_path As String) As String
   Dim connString As String
   Dim dbMaintPort As OleDb.OleDbConnection
   Dim ValidConnection As Boolean
   Dim finalConnection As String
   Dim connStrings(2) As String
   connStrings(0) = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & mdb_path
   connStrings(1) = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mdb_path
   connStrings(2) = "AnyOtherProviderTestConnectionStrings..."

   ValidConnection = False
   For value As Integer = 0 To 2
      Try
         dbMaintPort = New OleDb.OleDbConnection(connStrings(value))
         dbMaintPort.Open()
         dbMaintPort.Close()

         MsgBox("Success: " & connStrings(value))
         ValidConnection = True
         finalConnection = connStrings(value)
      Catch 
      End Try

      if ValidConnection
         exit
      endif 

   Next

   ; continue with whatever else you want to do with test result and final string

End Function

另外,您看过 ConnectionStrings.com 吗?他们可能会为您提供更多选项和连接示例,以测试不同的提供商等。

于 2013-02-05T04:09:03.690 回答