VB6•Create and Delete the DSN Connection

Listing 2. Create and delete the DSN connection using the SQLConfigDataSource API function. Open a default form with two command buttons—cmdCreate and cmdDelete. Declare the constants and function in the Declaration section of the form.

Option Explicit
Private Const ODBC_ADD_DSN = 1
Private Const ODBC_REMOVE_DSN = 3
Private Const vbAPINull As Long = 0&
Private Declare Function SQLConfigDataSource Lib _
   "ODBCCP32.DLL" (ByVal hwndParent As Long, _
   ByVal fRequest As Long, ByVal lpszDriver As String, _
   ByVal lpszAttributes As String) As Long
'/*On the click event of the cmdCreate */
   Private Sub cmdCreate _Click()
      Dim lResult As Long      
      Dim sDriver As String
      Dim sAttr As String

10   sDriver = "SQL Server"
     '/*Set the attributes :*/
20   sAttr = "SERVER=MyServer" & Chr$(0)
30   sAttr = strAttr & "DESCRIPTION=MyDSN" & Chr$(0)
40   sAttr = strAttr & "DSN=SQL Server" & Chr$(0)
50   sAttr = strAttr & "DATABASE=MyDatabaseName" & Chr$(0)

60   lResult = SQLConfigDataSource(vbAPINull, ODBC_ADD_DSN , _
     sDriver, sAttr)
70   If lResult Then
     	MsgBox "DSN Created Successfully!"
80   Else
90      MsgBox "DSN has not been Created."
   End If
End Sub
'/* To delete DSN add the following code to the click event of 
'/* the cmdDelete 
Private Sub cmdDelete_Click
   Dim lResult As Long
   Dim sDriver As String
   Dim  sAttr As String

10   sDriver = "SQL Server"
20   sAttr = "DSN=MyDSN" & Chr$(0)
30   lResult = SQLConfigDataSource(vbAPINull, ODBC_REMOVE_DSN , _
     	sDriver, sAttr)
40   If lResult Then
50      MsgBox "DSN Deleted!"
60   Else
70      MsgBox "DSN has not been Deleted!"
80   End If

End Sub