Friday, February 8, 2008

Creating a system DSN entry with VB.Net 2005

I needed to create a ODBC driver that will attach to the database I need to access for my program. The goal is to do as little manually as possible, which means I need to write code to create this ODBC driver.

First of all, many thanks to Paul Clement whose post was able to get my last bug out and the code working correctly. (See his post at http://www.mcse.ms/message1068199.html)

Here is my code:



Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" (ByVal hwndParent As Integer, ByVal ByValfRequest As Integer, ByVal lpszDriver As String, ByVal lpszAttributes As String) As Integer


Private Const ODBC_ADD_SYS_DSN As Short = 4


Private Const vbAPINull As Int32 = 0



Public Function CreateODBC(ByVal szDSNName As String, ByVal szServerName As String, ByVal szDatabase As String) As Boolean


Dim szAttributes As String = ""


Dim szDriver As String = "SQL Server" '//Set to SQL Server as it is the most common


Dim lReturnValue As Int32 = 0



Try


szAttributes = szAttributes & "Server=" & szServerName & Chr(0)


szAttributes = szAttributes & "DESCRIPTION=Test" & Chr(0)


szAttributes = szAttributes & "DSN=" & szDSNName & Chr(0)



szAttributes = szAttributes & "Database=" & szDatabase & Chr(0)


szAttributes = szAttributes & "Trusted_connection=YES" & Chr(0)



'//To show dialog, use Form1.Hwnd instead of vbAPINull


lReturnValue = SQLConfigDataSource(vbAPINull, ODBC_ADD_SYS_DSN, szDriver, szAttributes)



If lReturnValue <> 0 Then


Return True


Else


Return False


End If


Catch ex As Exception


RptError("Unable to create the ODBC", ex)


Return False


End Try


End Function


No comments: