将 SQL Server 凭据添加到 ADO 连接

Posted

技术标签:

【中文标题】将 SQL Server 凭据添加到 ADO 连接【英文标题】:Adding SQL Server Credentials to ADO Connection 【发布时间】:2022-01-06 02:17:01 【问题描述】:

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

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

主要问题似乎是用户名和密码不正确。我不确定下面哪里可以添加 SQL Server 的系统管理员 (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

【问题讨论】:

【参考方案1】:

如果您使用Trusted_Connection=yes,SQL 服务器会通过 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

【讨论】:

虽然@FunThomas 已经回答了您的问题,但请允许我将网站ConnectionStrings.com 添加为资源。

以上是关于将 SQL Server 凭据添加到 ADO 连接的主要内容,如果未能解决你的问题,请参考以下文章

使用 ADO.Net 数据集将数据插入 SQl Server 数据库

VC++用ADO连接SQL Server出错,异常:“Unknown error 0x800A0E7D".提示:“数据库连接失败”.

ado连接sql server

SSIS 将 ADO Net 源聚合到 SQL Server 数据库中

ADO数据库连接字符串(sql server数据库)

.NET/SQL Server 数据库连接分析详解