Como criar uma ligação sem DSN para SQL Server para tabelas ligadas no Access

Avançado: requer codificação especializada, interoperabilidade e competências multiutilizadas.

Este artigo aplica-se apenas a uma base de dados do Microsoft Access (.accdb ou .mdb).

Introdução

Este artigo descreve como criar uma ligação ao Microsoft SQL Server para tabelas ligadas no Microsoft Access que não utilizem um nome de origem de dados (DSN). Também é conhecida como uma ligação sem DSN.

Mais informações

Pode utilizar um DSN para criar tabelas de SQL Server ligadas no Microsoft Access. No entanto, quando move a base de dados para outro computador, tem de recriar o DSN nesse computador. Este procedimento pode ser problemático quando tem de o efetuar em mais do que um computador. Quando este procedimento não é executado corretamente, as tabelas ligadas poderão não conseguir localizar o DSN. Por conseguinte, as tabelas ligadas podem não conseguir ligar-se a SQL Server.

Quando quiser criar uma ligação para uma tabela de SQL Server, mas não quiser codificar um DSN na caixa de diálogo Origens de Dados, utilize um dos seguintes métodos para criar uma ligação sem DSN para SQL Server.

Método 1: Utilizar o método CreateTableDef

O método CreateTableDef permite-lhe criar uma tabela ligada. Para utilizar este método, crie um novo módulo e, em seguida, adicione a seguinte função AttachDSNLessTable ao novo 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 obter mais informações sobre os parâmetros do método CreateTableDef, veja Database.CreateTableDef method (DAO) (Método Database.CreateTableDef [DAO].

Para chamar a função AttachDSNLessTable, adicione código semelhante a um dos seguintes exemplos de código na macro Exec Automático ou no formulário de arranque Form_Open evento:

  • Quando utilizar a macro Exec Automático, chame a função AttachDSNLessTable e, em seguida, transmita parâmetros semelhantes aos seguintes da ação RunCode.

        AttachDSNLessTable ("authors", "authors", "(local)", "pubs", "", "")
    
  • Quando utilizar o formulário de arranque, adicione código semelhante ao seguinte ao 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 Tem de ajustar a lógica de programação quando adicionar mais do que uma tabela ligada à base de dados do Access.

Método 2: utilizar o DAO. RegisterDatabase method (Método RegisterDatabase)

O DAO. O método RegisterDatabase permite-lhe criar uma ligação DSN na macro Exec Automático ou no formulário de arranque. Embora este método não remova o requisito de uma ligação DSN, ajuda a resolver o problema ao criar a ligação DSN no código. Para utilizar este método, crie um novo módulo e, em seguida, adicione a seguinte função CreateDSNConnection ao novo 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 Se o método RegisterDatabase for novamente chamado, o DSN é atualizado.

Para chamar a função CreateDSNConnection, adicione código semelhante a um dos seguintes exemplos de código na macro Auto-Exec ou no formulário de arranque Form_Open evento:

  • Quando utilizar a macro Exec Automático, chame a função CreateDSNConnection e, em seguida, transmita parâmetros semelhantes aos seguintes da ação RunCode.

        CreateDSNConnection ("(local)", "pubs", "", "")
    
  • Quando utilizar o formulário de arranque, adicione código semelhante ao seguinte ao 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 pressupõe que já criou o SQL Server tabelas ligadas na base de dados do Access ao utilizar "myDSN" como o nome do DSN.