-1

我尽力使用 VB.NET 为 Access (.accdb) 数据库添加 ODBC 系统数据源。从谷歌搜索我尝试了很多功能,但没有任何效果。

我试过的代码是:

Sub createDSN()

    Const ODBC_ADD_SYS_DSN = 4 ' Add data source
    Dim dbpath As String = "C:\Jenit\Data\001.accdb"

    Dim ret As Integer, Driver As String, Attributes As String

    Driver = "Microsoft Access Driver (*.MDB,*.accdb)" & Chr(0)
    Attributes = "DSN=" & "Hello" & Chr(0)
    Attributes = Attributes & "Uid=Admin" & Chr(0) & "pwd=pwd" & Chr(0)
    Attributes = Attributes & "DBQ=" & dbpath & Chr(0) & Chr(0)

    ret = SQLConfigDataSource(0&, ODBC_ADD_SYS_DSN, Driver, Attributes) 'Error Here


    'ret is equal to 1 on success and 0 if there is an error
    If ret <> 1 Then
        MsgBox("DSN Creation Failed")
    Else
        MsgBox("Successful")
    End If
End Sub 'Main

错误是:

调用 PInvoke 函数 'j!j.Form1::SQLConfigDataSource' 使堆栈失衡。这可能是因为托管 PInvoke 签名与非托管目标签名不匹配。检查 PInvoke 签名的调用约定和参数是否与目标非托管签名匹配。

请帮忙。

4

1 回答 1

1

没有看到你的<DllImport>陈述,很难给你一个确切的答案,但我做出了有根据的猜测(基于 pinvoke.net 上的sqlconfigdatasource (odbccp32))和你提供的代码,你已经将你的SQLConfigDataSource函数定义为这样的东西:

Public Shared Function SQLConfigDataSourceW(ByVal hwndParent As Long, ByVal fRequest As Integer, ByVal lpszDriver As String, ByVal lpszAttributes As String) As Integer

实际上hwndParent是一个 32 位整数(Integer在 VB.NET 中),所以它应该看起来像这样:

Public Shared Function SQLConfigDataSourceW(ByVal hwndParent As Integer, ByVal fRequest As Integer, ByVal lpszDriver As String, ByVal lpszAttributes As String) As Integer

你会这样称呼它:

ret = SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, Driver, Attributes)

注意0是一个Integer,而是0&一个Long

编辑 来自 pinvoke.net:

<DllImport("ODBCCP32.dll",CallingConvention:=CallingConvention.WinAPI,CharSet:=CharSet.Unicode,SetLastError:=True)>
Public Shared Function SQLConfigDataSourceW(ByVal hwndParent As Integer, ByVal fRequest As Integer, ByVal lpszDriver As String, ByVal lpszAttributes As String) As Integer

然后只需替换您当前的行

ret = SQLConfigDataSource(0&, ODBC_ADD_SYS_DSN, Driver, Attributes)

有了这个:

ret = SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, Driver, Attributes)
于 2013-09-05T08:38:48.060 回答