Artículo : Q171146
En la versión 32 bits de VB es posible usar conexiones sin DSN, pero como la versión de 16 bits del
ODBC no puede manejar esta sintaxis no es posible hacerlo con el VB 4.0 16. Podemos simularlo
creando y eliminando dinámicamente el DSN empleando la función SQLConfigDataSource del API de
ODBC.
Los siguientes ejemplos en 16 y 32 bits muestran esta técnica. Se ha incluído código de 32 bits porque
tiene también otros usos que veremos a continuación. Las técnicas de 32 bits presentadas pueden
aplicarse también en VB 5.0.
El poder establecer una conexión sin DSN tiene ventajas:
1 - Simplicidad. El usuario no necesita preocuparse de crear el DSN, nombrarlo correctamente, establecer
sus opciones, etc. Esto lo hace dinámicamente la aplicación.
2 - Incrementa la flexibilidad de la aplicación.
Todo esto puede ser realizado en ODBC de 16 bits creando y eliminando un DSN dinámicamente. Este
método es útil también para un manejo simple de DSN. Podremos crear, modificar y eliminar DSNs en
cualquier momento. Visual Basic permite crear un DSN empleando el método
DBEngine.RegisterDatabase, pero el API de ODBC nos da mayor funcionalidad y la posibilidad de
modificar y eliminar un DSN también.
Declaramos las constantes y funciones necesarias :
'declaracion de constantes
Private Const ODBC_ADD_DSN = 1 ' Add data source
Private Const ODBC_CONFIG_DSN = 2 ' Configure (edit) data source
Private Const ODBC_REMOVE_DSN = 3 ' Remove data source
Private Const vbAPINull As Long = 0& ' NULL Pointer
'delcaracion de funciones
#If Win32 Then
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
#Else
Private Declare Function SQLConfigDataSource Lib "ODBCINST.DLL" _
(ByVal hwndParent As Integer, ByVal fRequest As Integer, ByVal _
lpszDriver As String, ByVal lpszAttributes As String) As Integer
#End If
Para crear un DSN :
#If Win32 Then
Dim intRet As Long
#Else
Dim intRet As Integer
#End If
Dim strDriver As String
Dim strAttributes As String
'usamos el driver de SQL Server porque es el mas comun
strDriver = "SQL Server"
'Asignamos los parametros separados por null.
strAttributes = "SERVER=SomeServer" & Chr$(0)
strAttributes = strAttributes & "DESCRIPTION=Temp DSN" & Chr$(0)
strAttributes = strAttributes & "DSN=DSN_TEMP" & Chr$(0)
strAttributes = strAttributes & "DATABASE=pubs" & Chr$(0)
strAttributes = strAttributes & "UID=sa" & Chr$(0)
strAttributes = strAttributes & "PWD=" & Chr$(0)
'Para mostrar el diálogo usar Form1.Hwnd en vez de vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_ADD_DSN, strDriver, strAttributes)
If intRet Then
MsgBox "DSN Creado"
Else
MsgBox "Fallo en la creación"
End If
Para borrarlo :
#If Win32 Then
Dim intRet As Long
#Else
Dim intRet As Integer
#End If
Dim strDriver As String
Dim strAttributes As String
'usamos el driver de SQL Server porque es el mas comun
strDriver = "SQL Server"
'Asignamos los parametros separados por null.
strAttributes = "DSN=DSN_TEMP" & Chr$(0)
'Para mostrar el diálogo usar Form1.Hwnd en vez de vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_REMOVE_DSN, strDriver, strAttributes)
If intRet Then
MsgBox "DSN Eliminado"
Else
MsgBox "Fallo en el borrado"
End If
Para modificarlo:
#If Win32 Then
Dim intRet As Long
#Else
Dim intRet As Integer
#End If
Dim strDriver As String
Dim strAttributes As String
'usamos el driver de SQL Server porque es el mas comun
strDriver = "SQL Server"
'Asignamos los parametros separados por null.
strAttributes = "SERVER=OtroSomeServer" & Chr$(0)
strAttributes = strAttributes & "DESCRIPTION=Temp DSN modificado" & Chr$(0)
strAttributes = strAttributes & "DSN=DSN_TEMP" & Chr$(0)
strAttributes = strAttributes & "DATABASE=pubs" & Chr$(0)
strAttributes = strAttributes & "UID=sa" & Chr$(0)
strAttributes = strAttributes & "PWD=" & Chr$(0)
'Para mostrar el diálogo usar Form1.Hwnd en vez de vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_CONFIG_DSN, strDriver, strAttributes)
If intRet Then
MsgBox "DSN Modificado"
Else
MsgBox "Fallo en la modificacion"
End If
Nota
Si el DSN es para access hay que tener en cuenta :
- En vez de DATABASE debes usar DBQ y especificar el nombre completo de la base de datos, incluyendo el path y la extension.
- El UID por defecto es admin, aunque en la base de datos este en español y se llame administrador.
Si tienes problemas lo mas sencillo es que hagas un dsn de fichero (File Dsn) y luego con el notepad lo editas y puedes ver los parametros que usa.