Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCreate a DSN in code
KeywordsDSN, database
CategoriesDatabase
 
Thanks to Craig.

Use the SQLConfigDataSource routine in odbccp32.dll.

This example makes a couple of API calls so it's best to check if your system is compatible and if you have those dll's on your system and that they 32 bit. This example also uses the Common Dialog control (SP3). It doesn't make use of any major features of the Common Dialog so a normal Common Dialog can be used if the current reference causes an error.

 
Public Sub ConfigureSystemDSN(ByVal sDSN As String, _
   ByVal sDriver As String, _
   ByVal sDBFile As String, _
   ByVal eAction As ACTION _
   )

   Dim sAttributes   As String
   Dim sDBQ          As String
   Dim sRegValue     As String
   Dim lRetVal       As Long
   Dim hKey          As Long
   Dim lValueType    As Long
   Dim sMessage      As String

   If RegOpenKeyEx(HKEY_CURRENT_USER, _
      "Software\ODBC\ODBC.INI\" & sDSN, _
      0, _
      KEY_ALL_ACCESS, hKey _
      ) = 0 Then

      sRegValue = String(1024, 0)

      If RegQueryValueEx(hKey, _
         "DBQ", _
         0, _
         lValueType, _
         sRegValue, _
         Len(sRegValue) _
         ) = 0 Then

         If lValueType = REG_SZ Then
            sDBQ = Left(sRegValue, InStr(sRegValue, _
                vbNullChar) - 1)
         End If
      End If

      RegCloseKey hKey
   End If

   If (sDBQ = "" And (eAction = ODBC_ADD_DSN Or eAction = _
       ODBC_ADD_SYS_DSN)) _
   Or _
      (sDBQ <> "" And (eAction = ODBC_REMOVE_DSN Or eAction _
          = ODBC_CONFIGURE_DSN)) Then

      If Len(Dir(sDBFile)) = 0 Then
         MsgBox "Database file doesn't exist!", vbOKOnly + _
             vbCritical, "Cannot Continue"
      Else
         sAttributes = "DSN=" & sDSN & vbNullChar & "DBQ=" _
             & sDBFile & vbNullChar
         lRetVal = SQLConfigDataSource(0&, eAction, _
             sDriver, sAttributes)
         MsgBox "Done!"
      End If
   Else
      If eAction = ODBC_ADD_DSN Or _
         eAction = ODBC_ADD_SYS_DSN Then

         sMessage = " already exists!"
      Else
         sMessage = " doesn't exist!"
      End If

      MsgBox "DSN: " & txtDsnName.Text & sMessage
   End If

End Sub

Private Sub cmdAddDSN_Click()
   ConfigureSystemDSN txtDsnName.Text, txtDriver.Text, _
       txtPathToData, ODBC_ADD_DSN
End Sub

Private Sub cmdDeleteDSN_Click()
   ConfigureSystemDSN txtDsnName.Text, txtDriver.Text, _
       txtPathToData, ODBC_REMOVE_DSN
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated