将 SQL 服务器凭据添加到 ADO 连接

Adding SQL Server Credentials to ADO Connection

我有一个 Excel 工作簿,它构建了一堆 SQL 更新脚本,然后在 SQL 服务器中执行它们。

我得到了以下 VBA 脚本的帮助。如果我 运行 在以管理员用户 Windows 身份登录时,下面的代码工作正常。但是,当 运行 从用户工作站我 运行 遇到问题时。

主要问题似乎是用户名和密码不正确。我不确定在下面的哪个位置可以为 SQL 服务器添加系统管理员 (sa) 用户名​​和密码。请给我一些帮助。

我的代码:

Sub test()

Const SERVER = "SRV\ServerName"
Const DATABASE = "Test Database"

Dim fso As Object, ts As Object, ar
Dim ws As Worksheet
Dim iLastRow As Long, i As Long
Dim sql As String, timestamp As String
Dim Folder As String, SQLfile As String, LOGfile As String
Dim t0 As String: t0 = Timer

' query file and log filenames
timestamp = Format(Now, "YYYYMMDD_HHMMSS")
Folder = "\SRV\Test Folder\"
SQLfile = Folder & timestamp & ".sql"
LOGfile = Folder & timestamp & ".log"

Set fso = CreateObject("Scripting.FileSystemObject")

' read data from sheet into array to build sql file
Set ws = ThisWorkbook.Sheets("UDF Update")
iLastRow = ws.Cells(Rows.Count, "N").End(xlUp).Row
If iLastRow = 1 Then
    MsgBox "No data in Column N", vbCritical
    Exit Sub
End If
ar = ws.Range("N2").Resize(iLastRow - 1).Value2

' connect to server and run query


    Dim sConn As String, conn, cmd, n As Long
    sConn = "Provider=SQLOLEDB;Server=" & SERVER & _
            ";Initial Catalog=" & DATABASE & _
            ";Trusted_Connection=yes;"

    ' open log file
    Set ts = fso.CreateTextFile(LOGfile)

    ' make connection
    Set conn = CreateObject("ADODB.Connection")
    conn.Open sConn

    ' execute sql statements
    Set cmd = CreateObject("ADODB.Command")
    With cmd
        .ActiveConnection = conn
        For i = 1 To UBound(ar)
            ts.writeLine ar(i, 1)
            .CommandText = ar(i, 1)
            .Execute
            
    On Error Resume Next
    Next
    End With
    ts.Close
    conn.Close
    MsgBox UBound(ar) & " SQL queries completed (ADODB)", vbInformation, Format(Timer - t0, "0.0 secs")


End Sub

如果您使用 Trusted_Connection=yes,SQL 服务器 accepts/rejects 您将通过 Windows 身份验证。似乎您的管理员帐户已被服务器接受,而其他帐户未被服务器接受。
其他帐户由数据库管理员添加到数据库服务器,或者您需要提供凭据并设置 Trusted_Connection=no(或省略它,因为这是默认设置)

sConn = "Provider=SQLOLEDB;Server=" & SERVER & _
        ";Initial Catalog=" & DATABASE & _
        ";Trusted_Connection=no" & _
        ";User ID=MyUserID;Password=MyPassword;"

https://docs.microsoft.com/en-us/sql/ado/guide/appendixes/microsoft-ole-db-provider-for-sql-server?view=sql-server-ver15