本指南介绍了如何 MicrosoftAccess 不使用数据源名称 (DSN) 中为链接表创建一个连接到 MicrosoftSQLServer。 这将也称作 DSN 的连接。 对本文包含示例适用于 Microsoft Office Access 2007年、 到 Microsoft Office Access 2003, 和到 Microsoft Access 2002。
可用于 DSN MicrosoftAccess 中创建链接 SQLServer 表。 但当您将数据库移动到其他计算机, 必须重新创建该计算机上 DSN。 当需要多个计算机上执行该过程可能有问题。 当正确, 不执行此过程链接表可能无法以定位 DSN。 因此, 链接表可能无法以连接到 SQLServer。
您要创建链接到 SQLServer 表但不想硬编码到 数据源 对话框中, DSN 时使用下列方法之一来创建 DSN 的连接到 SQLServer。
一、解决方案如下:
方法 1: 使用 CreateTableDef 方法
CreateTableDef 方法允许您创建链接表。 要使用此方法, 创建一个新模块, 然后将以下 AttachDSNLessTable 函数添加到新模块。
'//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
要调用 AttachDSNLessTable 函数, 添加代码是类似于之一以下代码示例在 Autoexec 宏中或启动窗体 Form_Open 事件中: • 使用 Autoexec, 时调用 AttachDSNLessTable 函数, 并然后传递参数是从 RunCode 操作类似于以下。
AttachDSNLessTable ("authors", "authors", "(local)", "pubs", "", "")
• 当您使用启动窗体, 添加是类似于以下以 Form_Open 事件代码。
Private Sub