Jak utworzyć połączenie bez nazwY DSN z SQL Server dla tabel połączonych w programie Access

Zaawansowane: wymaga specjalistycznego kodowania, współdziałania i wielodostępnych umiejętności.

Ten artykuł dotyczy tylko bazy danych programu Microsoft Access (.mdb lub .accdb).

Wprowadzenie

W tym artykule opisano sposób tworzenia połączenia z usługą Microsoft SQL Server dla tabel połączonych w programie Microsoft Access, które nie używają nazwy źródła danych (DSN). Jest to również nazywane połączeniem bez nazwy DSN.

Więcej informacji

Za pomocą nazwy DSN można utworzyć połączone tabele SQL Server w programie Microsoft Access. Jednak po przeniesieniu bazy danych na inny komputer należy ponownie utworzyć nazwę DSN na tym komputerze. Ta procedura może być problematyczna, gdy trzeba ją wykonać na więcej niż jednym komputerze. Jeśli ta procedura nie zostanie wykonana poprawnie, połączone tabele mogą nie być w stanie zlokalizować nazwy DSN. W związku z tym tabele połączone mogą nie być w stanie nawiązać połączenia z SQL Server.

Jeśli chcesz utworzyć link do tabeli SQL Server, ale nie chcesz na stałe kodować nazwy DSN w oknie dialogowym Źródła danych, użyj jednej z następujących metod, aby utworzyć połączenie bez nazwy DSN do SQL Server.

Metoda 1. Używanie metody CreateTableDef

Metoda CreateTableDef umożliwia utworzenie tabeli połączonej. Aby użyć tej metody, utwórz nowy moduł, a następnie dodaj następującą funkcję AttachDSNLessTable do nowego modułu.

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

Aby uzyskać więcej informacji na temat parametrów metody CreateTableDef, zobacz Database.CreateTableDef, metoda (DAO).

Aby wywołać funkcję AttachDSNLessTable, dodaj kod podobny do jednego z następujących przykładów kodu w makrze Auto-Exec lub w formularzu uruchamiania Form_Open zdarzenia:

  • W przypadku korzystania z makra Auto-Exec wywołaj funkcję AttachDSNLessTable, a następnie przekaż parametry podobne do następujących z akcji RunCode.

        AttachDSNLessTable ("authors", "authors", "(local)", "pubs", "", "")
    
  • Podczas korzystania z formularza uruchamiania dodaj kod podobny do następującego do zdarzenia 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
    

Uwaga Logikę programowania należy dostosować, dodając więcej niż jedną połączoną tabelę do bazy danych programu Access.

Metoda 2. Używanie obiektu DAO. RegisterDatabase, metoda

The DAO. Metoda RegisterDatabase umożliwia utworzenie połączenia DSN w makrach Auto-Exec lub w formularzu uruchamiania. Chociaż ta metoda nie usuwa wymagania dotyczącego połączenia DSN, ułatwia rozwiązanie problemu przez utworzenie połączenia DSN w kodzie. Aby użyć tej metody, utwórz nowy moduł, a następnie dodaj następującą funkcję CreateDSNConnection do nowego modułu.

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

Uwaga Jeśli metoda RegisterDatabase zostanie wywołana ponownie, nazwa DSN zostanie zaktualizowana.

Aby wywołać funkcję CreateDSNConnection, dodaj kod podobny do jednego z następujących przykładów kodu w makrze Auto-Exec lub w formularzu uruchamiania Form_Open zdarzenia:

  • W przypadku korzystania z makra Auto-Exec wywołaj funkcję CreateDSNConnection, a następnie przekaż parametry podobne do poniższych z akcji RunCode.

        CreateDSNConnection ("(local)", "pubs", "", "")
    
  • Podczas korzystania z formularza uruchamiania dodaj kod podobny do następującego do zdarzenia Form_Open.

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

Uwaga

Ta metoda zakłada, że utworzono już tabele połączone SQL Server w bazie danych programu Access przy użyciu nazwy "myDSN" jako nazwy DSN.