Come creare una connessione senza DSN a SQL Server per le tabelle collegate in Access

Avanzate: richiede competenze esperte di codifica, interoperabilità e multiutente.

Questo articolo si applica solo a un database di Microsoft Access (con estensioni .accdb e .mdb).

Introduzione

Questo articolo descrive come creare una connessione a Microsoft SQL Server per le tabelle collegate in Microsoft Access che non usa un nome di origine dati (DSN). È noto anche come connessione senza DSN.

Ulteriori informazioni

È possibile usare un DSN per creare tabelle SQL Server collegate in Microsoft Access. Tuttavia, quando si sposta il database in un altro computer, è necessario ricreare il DSN in tale computer. Questa procedura può risultare problematica quando è necessario eseguirla in più computer. Quando questa procedura non viene eseguita correttamente, le tabelle collegate potrebbero non essere in grado di individuare il DSN. Pertanto, le tabelle collegate potrebbero non essere in grado di connettersi a SQL Server.

Quando si desidera creare un collegamento a una tabella SQL Server ma non si vuole hardcodedizzare un DSN nella finestra di dialogo Origini dati, utilizzare uno dei metodi seguenti per creare una connessione senza DSN a SQL Server.

Metodo 1: usare il metodo CreateTableDef

Il metodo CreateTableDef consente di creare una tabella collegata. Per usare questo metodo, creare un nuovo modulo e quindi aggiungere la funzione AttachDSNLessTable seguente al nuovo modulo.

'//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

Per altre informazioni sui parametri del metodo CreateTableDef, vedere Metodo Database.CreateTableDef (DAO).

Per chiamare la funzione AttachDSNLessTable, aggiungere codice simile a uno degli esempi di codice seguenti nella macro Auto-Exec o nel modulo di avvio Form_Open evento:

  • Quando si usa la macro Auto-Exec, chiamare la funzione AttachDSNLessTable e quindi passare parametri simili al seguente dall'azione RunCode.

        AttachDSNLessTable ("authors", "authors", "(local)", "pubs", "", "")
    
  • Quando si usa il modulo di avvio, aggiungere codice simile al seguente all'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 È necessario modificare la logica di programmazione quando si aggiungono più tabelle collegate al database di Access.

Metodo 2: usare l'oggetto DAO. Metodo RegisterDatabase

Oggetto DAO. Il metodo RegisterDatabase consente di creare una connessione DSN nella macro Auto-Exec o nel modulo di avvio. Anche se questo metodo non rimuove il requisito per una connessione DSN, consente di risolvere il problema creando la connessione DSN nel codice. Per usare questo metodo, creare un nuovo modulo e quindi aggiungere la funzione CreateDSNConnection seguente al nuovo modulo.

'//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 Se il metodo RegisterDatabase viene chiamato di nuovo, il DSN viene aggiornato.

Per chiamare la funzione CreateDSNConnection, aggiungere codice simile a uno degli esempi di codice seguenti nella macro Auto-Exec o nel modulo di avvio Form_Open evento:

  • Quando si usa la macro Auto-Exec, chiamare la funzione CreateDSNConnection e quindi passare parametri simili ai seguenti dall'azione RunCode.

        CreateDSNConnection ("(local)", "pubs", "", "")
    
  • Quando si usa il modulo di avvio, aggiungere codice simile al seguente all'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

Questo metodo presuppone che sia già stata creata la SQL Server tabelle collegate nel database di Access usando "myDSN" come nome DSN.