如何为Access数据库添加ODBC系统DSN?

时间:2013-09-05 05:26:24

标签: vb.net odbc dsn

我尽力使用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签名的调用约定和参数是否与目标非托管签名匹配。

请帮助。

1 个答案:

答案 0 :(得分: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位整数(VB.NET中为Integer),所以看起来应该是这样的:

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)

注意0Integer,而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)