I need a programmatic way of creating a SQL Server ODBC Data Source. I can do this by directly accessing the Registry. It would be better if this could be done via an available (SQL Server/Windows) API to protect against changes in the registry keys or values with updated SQL Server drivers.
Accepted Answer Note: Using SQLConfigDataSource abstracts the code from the details of Registry keys etc. so this is more robust. I was hoping, however, that SQL Server would have wrapped this with a higher level function which took strongly typed attributes (rather than a delimited string) and exposed it through the driver.
SQLConfigDataSource() does the job.
MSDN article
Just in case here is a VB6 example:
Const ODBC_ADD_DSN = 1 'user data source
Const ODBC_ADD_SYS_DSN = 4 'system data source
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
strDriver = "SQL Server"
strAttributes = "DSN=Sample" & Chr$(0) _
& "Database=Northwind" & Chr$(0) _
& "Description= Sample Data Source" & Chr$(0) _
& "Server=(local)" & Chr$(0) _
& "Trusted_Connection=No" & Chr$(0)
SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes)
For VB.NET it can be done this way:
Import for 'DllImport':
Imports System.Runtime.InteropServices
Declaration of SQLConfigDataSource:
<DllImport("ODBCCP32.DLL")> Shared Function SQLConfigDataSource _
(ByVal hwndParent As Integer, ByVal fRequest As Integer, _
ByVal lpszDriver As String, _
ByVal lpszAttributes As String) As Boolean
End Function
Example usage:
Const ODBC_ADD_DSN = 1 'User data source
Const ODBC_ADD_SYS_DSN = 4 'System data source
Public Function CreateSqlServerDataSource
Dim strDriver As String : strDriver = "SQL Server"
Dim strAttributes As String : strAttributes = _
"DSN=Sample" & Chr(0) & _
"Database=Northwind" & Chr(0) & _
"Description= Sample Data Source" & Chr(0) & _
"Server=(local)" & Chr(0) & _
"Trusted_Connection=No" & Chr(0)
SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes)
End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With