How to add ODBC System DSN for Access Database?

2k Views Asked by At

I tried My best to add ODBC System Data Source for Access (.accdb) Database using VB.NET. Searching from Google I tried many Functions but nothing worked.

Code I tried is :

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

Error is :

A call to PInvoke function 'j!j.Form1::SQLConfigDataSource' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

Please Help.

1

There are 1 best solutions below

2
On

Without seeing your <DllImport> statement, it's difficult to give you an exact answer, but I'm making an educated guess (based on sqlconfigdatasource (odbccp32) at pinvoke.net) and the code you provided that you've defined your SQLConfigDataSource function as something like this:

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

When in reality hwndParent is an 32-bit integer (Integer in VB.NET), so it should look something like this:

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

The you would call it like this:

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

Note 0 is an Integer, whereas 0& is a Long.

EDIT From 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

Then simply replace your current line

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

With this:

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