通过 VBA (ADODB) 连接到 Microsoft SQL 数据库,破坏数据库的风险最低

Connection to a Microsoft SQL Database via VBA (ADODB) with the lowest risk to harm the database

我目前正在寻找一种通过 VBA (ADODB) 连接到 Microsoft SQL 服务器数据库的方法,重点是将破坏、阻止和更改数据库结构的风险降到最低.因此访问是只读的。

我的尝试如下:

Set DBConn = New ADODB.Connection
Set TmpRecset = New Recordset

DBConn.ConnectionString = pConnStr
DBConn.Open

On Error GoTo TermConnection

With TmpRecset
    .ActiveConnection = DBConn
    .Source = pQuery
    .LockType = adLockReadOnly
    .CursorType = adOpenForwardOnly
    .CursorLocation = adUseClient
    .Open
End With

On Error GoTo TermRecordset

//Doing something useful with TmpRecset

On Error GoTo 0

TermRecordset:
TmpRecset.Close
Set TmpRecset.ActiveConnection = Nothing

TermConnection:
DBConn.Close
Set DBConn = Nothing

End Sub

我正在使用以下连接字符串:

"Provider=SQLOLEDB;Data Source=IP\Database;Initial Catalog=Databasename;Trusted_connection=yes;"

我使用手动错误处理来确保无论发生什么情况,记录集和数据库都会关闭。通过记录集的参数,我定义了只读访问权限。

是否有其他机制可以确保数据库的完整性?

此致

在我看来 Excel 没有合理的安全保障。所有安全性都应驻留在服务器上。如果要防止对数据库进行意外或恶意更改,则服务器上的数据库应该是只读的,或者所有用户都应该对 SQL 服务器具有只读访问权限。此外,您可以在服务器上实施跟踪,SQL 审计 C2,或使用扩展属性。然而,所有这些都在 SQL 服务器端。您可以在 "client" 方面做的事情(例如本例中的 Excel)只是支持功能。所以问题是(对我来说)我可以在 Excel 中实现什么样的支持功能来确保 SQL 服务器安全。以下是我所做的一些事情:

(1) 使用全局变量或将字符串存储在隐藏 sheet 上使连接字符串动态化。然后就可以在开发服务器和生产服务器之间自动切换了。示例:

Dim conRCServer As ADODB.Connection
Dim rstResult As ADODB.Recordset
Dim strSQL As String

Set conRCServer = New ADODB.Connection
conRCServer.ConnectionString = "PROVIDER=SQLOLEDB; " _
    & "DATA SOURCE=" & Ref.Range("C2").Value2 & ";" _
    & "INITIAL CATALOG=" & Ref.Range("C4").Value & ";" _
    & "Integrated Security=SSPI "
On Error GoTo SQL_ConnectionError
conRCServer.Open
On Error GoTo 0

(2) 有一个单独的错误处理程序来连接到服务器并处理 SQL 语法错误。示例:

Set rstResult = New ADODB.Recordset
strSQL = "set nocount on; "
strSQL = strSQL & "/* #" & ActiveWorkbook.Path & "/" & ActiveWorkbook.Name & "{" & WorksheetUsers.Name & "}btnDownloadUserDataFromServer */"
strSQL = strSQL & "select  v.LastName, "
strSQL = strSQL & "        v.FirstName "
strSQL = strSQL & "from    vUsers as v "
strSQL = strSQL & "order by v.LastName, v.FirstName "
rstResult.ActiveConnection = conRCServer
On Error GoTo SQL_StatementError
rstResult.Open strSQL
On Error GoTo 0

这是 SQL 语法的错误处理程序,在上面的示例中是可能的 SQL 连接错误的单独处理程序。

(3) 在 SQL 语法中加入自我识别。正如您在上面的示例中看到的,我还让服务器知道用户调用了哪个文件、哪个 sheet(在文件中)以及 sheet 中的哪个函数来执行此语句。如果您使用跟踪在服务器上捕获此数据,那么您可以看到谁在编写他们自己的查询,谁在使用您的标准文件以及使用了哪些函数(以及它们各自的影响)。

(4) 如果发生错误,您可能需要考虑编写自动错误电子邮件。示例:

SQL_ConnectionError:
Y = MsgBox("Cannot connect to the server. Please make sure that you have a working internet connection. " & _
            "Also ensure that are connected to the corporate network and are allowed to access the server. " & _
            "Do you want me to prepare an error-email?", 52, "Problems connecting to Server...")
If Y = 6 Then
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
        .to = Ref.Range("C7").Value2
        .CC = Ref.Range("C8").Value2
        .Subject = "Problems connecting to database '" & Ref.Range("C4").Value & "' on server '" & Ref.Range("C2").Value & "'"
        .HTMLBody = "<span style=""font-size:10px"">---Automatically generated Error-Email---" & _
                "</span><br><br>Error report from the file '" & _
                "<span style=""color:blue"">" & ActiveWorkbook.Name & _
                "</span>' located and saved on '<span style=""color:blue"">" & _
                ActiveWorkbook.Path & "</span>'.<br>" & _
                "Excel is not able to establish a connection to the server. Technical data to follow." & "<br><br>" & _
                "Computer Name:    <span style=""color:green;"">" & Environ("COMPUTERNAME") & "</span><br>" & _
                "Logged in as:     <span style=""color:green;"">" & Environ("USERDOMAIN") & "/" & Environ("USERNAME") & "</span><br>" & _
                "Domain Server:    <span style=""color:green;"">" & Environ("LOGONSERVER") & "</span><br>" & _
                "User DNS Domain:  <span style=""color:green;"">" & Environ("USERDNSDOMAIN") & "</span><br>" & _
                "Operating System: <span style=""color:green;"">" & Environ("OS") & "</span><br>" & _
                "Excel Version:    <span style=""color:green;"">" & Application.Version & "</span><br>" & _
                "<br><span style=""font-size:10px""><br>" & _
                "Possible reasons for this error include: (1) no Internet connection, (2) no working VPN connection to the corporate network, " & _
                "(3) the server is currently offline, (4) DNS authentication problems, (5) ... other reasons ..., " & _
                "(6) the user does not have the required permission to connect to the underlying database on the server." & _
                "<br><br>---Automatically generated Error-Email---"
        .Display
    End With
    Set OutMail = Nothing
    Set OutApp = Nothing
End If
Exit Sub

我还研究了您更改连接参数的方法。但是在我工作过的大多数公司环境中,这些连接参数已被覆盖(例如,ADODB.Connection.CommandTimeout 被服务器的每个用户 SQL 超时或 Windows 公司预设(如果存在)覆盖)。所以,他们没有为我工作。但以上对我和我过去几年工作的公司来说效果相当好。

如果这就是您一直在寻找的答案,请告诉我。