创建用于将 MS Access 链接到 Azure SQL 服务器的登录过程

Creating login procedure for Linking MS Access to Azure SQL server

我有一个 MS Access 程序,其中包含许多链接到 Azure SQL 服务器的 SQL table。理想情况下,我想通过弹出窗体创建一个登录过程,我会在其中询问用户凭据,然后我会在其中更新链接的 tables 并使用所需数据传递查询。但是我无法让它工作。代码 运行 很好,没有错误消息,但是当我 - 在执行该过程后 - 打开一个包含链接 table 的表单时,我仍然收到登录请求。这个想法是在启动屏幕上有登录过程 运行,用户在成功登录后不会被要求在任何地方输入凭据。

这是我为此使用的代码:

Public Function ConnectToAzureSQL(sServer As String, sDatabase As String, sUserName As String, sPassWord As String)

On Error GoTo Proc_err
Dim con As Object
Dim var As Variant
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strConnect As String
Set db = CurrentDb
Set con = CreateObject("ADODB.Connection")
strConnect = "DRIVER={ODBC Driver 17 for SQL Server}" & _
";Server=sServer" & _
";Database=sDatabase" & _
";UID=sUserName" & _
"PWD=sPassWord".
con.Open strConnect

For Each tdf In db.TableDefs
Debug.Print tdf.Name

    If Len(tdf.Connect) Then
        tdf.Connect = strConnect
        tdf.RefreshLink
    End If
Next

con.Close
Proc_exit:

MsgBox ("done")

Exit Function
Proc_err:
Debug.Print Err.Description & " : " & Str(Err.Number)
Resume Proc_exit

End Function

忘记说的是,这个方法使用的是SQL服务器登录方式。 幸运的是,我自己找到了答案。如果有人需要它,这里是程序。这种方法的缺点是登录数据是在连接字符串中捕获的。转念一想,我选择了带有 MFA 的 Azure Active Directory 登录方法,其中没有密码存储在您的应用程序中。

Public Function ConnectToAzureSQL(sServer, sDb, sUID, sPWD As String, bConn As Boolean)

On Error GoTo Proc_err
Dim con As Object
Dim var As Variant
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strConnect As String

Set db = CurrentDb
Set con = CreateObject("ADODB.Connection")
sConnect = "DRIVER={ODBC Driver 17 for SQL Server}" & _
";Server=" & sServer _
& ";Database=" & sDb _
& ";UID=" & sUID _
& ";PWD=" & sPWD

con.Open strConnect

bConn = True

DoCmd.OpenForm "Frm_Bericht"

For Each tdf In db.TableDefs
    If Len(tdf.Connect) Then
        tdf.Connect = strConnect & ";UID=" & sUID & ";PWD=" & sPWD
        Forms!Frm_Bericht.Caption = "Update verbinding naar tabel: " & tdf.Name
        tdf.RefreshLink
    End If
Next

con.Close

DoCmd.Close acForm, "Frm_Bericht"

Proc_exit:

Exit Function
Proc_err:
Debug.Print Err.Description & " : " & Str(Err.Number)
Resume Proc_exit

End Function