Cómo crear una conexión sin DSN a SQL Server para tablas vinculadas en Access

Avanzado: requiere conocimientos expertos de codificación, interoperabilidad y multiusuario.

Este artículo solo se refiere a una base de datos de Microsoft Access (.mdb o .accdb).

Introducción

En este artículo se describe cómo crear una conexión a Microsoft SQL Server para tablas vinculadas en Microsoft Access que no usan un nombre de origen de datos (DSN). También se conoce como conexión sin DSN.

Más información

Puede usar un DSN para crear tablas de SQL Server vinculadas en Microsoft Access. Pero al mover la base de datos a otro equipo, debe volver a crear el DSN en ese equipo. Este procedimiento puede ser problemático cuando tiene que realizarlo en más de un equipo. Cuando este procedimiento no se realiza correctamente, es posible que las tablas vinculadas no puedan localizar el DSN. Por lo tanto, es posible que las tablas vinculadas no puedan conectarse a SQL Server.

Si desea crear un vínculo a una tabla de SQL Server pero no desea codificar de forma rígida un DSN en el cuadro de diálogo Orígenes de datos, use uno de los métodos siguientes para crear una conexión sin DSN a SQL Server.

Método 1: Usar el método CreateTableDef

El método CreateTableDef permite crear una tabla vinculada. Para usar este método, cree un nuevo módulo y agregue la siguiente función AttachDSNLessTable al nuevo módulo.

'//Name     :   AttachDSNLessTable
'//Purpose  :   Create a linked table to SQL Server without using a DSN
'//Parameters
'//     stLocalTableName: Name of the table that you are creating in the current database
'//     stRemoteTableName: Name of the table that you are linking to on the SQL Server database
'//     stServer: Name of the SQL Server that you are linking to
'//     stDatabase: Name of the SQL Server database that you are linking to
'//     stUsername: Name of the SQL Server user who can connect to SQL Server, leave blank to use a Trusted Connection
'//     stPassword: SQL Server user password
Function AttachDSNLessTable(stLocalTableName As String, stRemoteTableName As String, stServer As String, stDatabase As String, Optional stUsername As String, Optional stPassword As String)
    On Error GoTo AttachDSNLessTable_Err
    Dim td As TableDef
    Dim stConnect As String

For Each td In CurrentDb.TableDefs
        If td.Name = stLocalTableName Then
            CurrentDb.TableDefs.Delete stLocalTableName
        End If
    Next

If Len(stUsername) = 0 Then
        '//Use trusted authentication if stUsername is not supplied.
        stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes"
    Else
        '//WARNING: This will save the username and the password with the linked table information.
        stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";UID=" & stUsername & ";PWD=" & stPassword
    End If
    Set td = CurrentDb.CreateTableDef(stLocalTableName, dbAttachSavePWD, stRemoteTableName, stConnect)
    CurrentDb.TableDefs.Append td
    AttachDSNLessTable = True
    Exit Function

AttachDSNLessTable_Err:

AttachDSNLessTable = False
    MsgBox "AttachDSNLessTable encountered an unexpected error: " & Err.Description

End Function

Para obtener más información sobre los parámetros del método CreateTableDef, vea Método Database.CreateTableDef (DAO).

Para llamar a la función AttachDSNLessTable, agregue código similar a uno de los ejemplos de código siguientes en la macro Auto-Exec o en el formulario de inicio Form_Open evento:

  • Cuando use la macro Auto-Exec, llame a la función AttachDSNLessTable y, a continuación, pase parámetros similares a los siguientes desde la acción RunCode.

        AttachDSNLessTable ("authors", "authors", "(local)", "pubs", "", "")
    
  • Cuando use el formulario de inicio, agregue código similar al siguiente al evento Form_Open.

    Private Sub Form_Open(Cancel As Integer)
        If AttachDSNLessTable("authors", "authors", "(local)", "pubs", "", "") Then
            '// All is okay.
        Else
            '// Not okay.
        End If
    End Sub
    

Nota Debe ajustar la lógica de programación al agregar más de una tabla vinculada a la base de datos de Access.

Método 2: Use el DAO. RegisterDatabase (método)

El DAO. El método RegisterDatabase permite crear una conexión DSN en la macro Auto-Exec o en el formulario de inicio. Aunque este método no elimina el requisito de una conexión DSN, le ayuda a resolver el problema mediante la creación de la conexión DSN en el código. Para usar este método, cree un nuevo módulo y agregue la siguiente función CreateDSNConnection al nuevo módulo.

'//Name     :   CreateDSNConnection
'//Purpose  :   Create a DSN to link tables to SQL Server
'//Parameters
'//     stServer: Name of SQL Server that you are linking to
'//     stDatabase: Name of the SQL Server database that you are linking to
'//     stUsername: Name of the SQL Server user who can connect to SQL Server, leave blank to use a Trusted Connection
'//     stPassword: SQL Server user password
Function CreateDSNConnection(stServer As String, stDatabase As String, Optional stUsername As String, Optional stPassword As String) As Boolean
    On Error GoTo CreateDSNConnection_Err

Dim stConnect As String

If Len(stUsername) = 0 Then
        '//Use trusted authentication if stUsername is not supplied.
        stConnect = "Description=myDSN" & vbCr & "SERVER=" & stServer & vbCr & "DATABASE=" & stDatabase & vbCr & "Trusted_Connection=Yes"
    Else
        stConnect = "Description=myDSN" & vbCr & "SERVER=" & stServer & vbCr & "DATABASE=" & stDatabase & vbCr 
    End If

DBEngine.RegisterDatabase "myDSN", "SQL Server", True, stConnect

'// Add error checking.
    CreateDSNConnection = True
    Exit Function
CreateDSNConnection_Err:

CreateDSNConnection = False
    MsgBox "CreateDSNConnection encountered an unexpected error: " & Err.Description

End Function

Nota Si se vuelve a llamar al método RegisterDatabase, se actualiza el DSN.

Para llamar a la función CreateDSNConnection, agregue código similar a uno de los ejemplos de código siguientes en la macro Auto-Exec o en el formulario de inicio Form_Open evento:

  • Cuando use la macro Auto-Exec, llame a la función CreateDSNConnection y, a continuación, pase parámetros similares a los siguientes desde la acción RunCode.

        CreateDSNConnection ("(local)", "pubs", "", "")
    
  • Cuando use el formulario de inicio, agregue código similar al siguiente al evento Form_Open.

    Private Sub Form_Open(Cancel As Integer)
        If CreateDSNConnection("(local)", "pubs", "", "") Then
            '// All is okay.
        Else
            '// Not okay.
        End If
    End Sub
    

Nota:

Este método supone que ya ha creado las tablas vinculadas SQL Server en la base de datos de Access mediante "myDSN" como nombre de DSN.