I am using ActiveX Data Objects 6.1 library in Excel VBA to access a SQL Server 2012 database. I can connect and run queries fine, but once connected there appears to be no way to determine which server the connection object is connected to, as the connectionString property does not return the same string that was used to open the connection:
Public Sub connectDB()
Dim conn As New Connection
Dim strServer As String, strDatabase As String, strUser As String, strPassword As String
strServer = "****": strDatabase = "****": strUser = "****": strPassword = "****"
conn.ConnectionString = "Driver={SQL Server};Server=" & strServer & ";Database=" & strDatabase & ";UID=" & strUser & ";PWD=" & strPassword
Debug.Print conn.ConnectionString
conn.Open
Debug.Print conn.ConnectionString
End Sub
Outputs:
Driver={SQL Server};Server=****;Database=****;UID=****;PWD=****
Provider=MSDASQL.1;
In other words, once the connection is open the connectionString property is reset to something unhelpful. Connection.DefaultDatabase returns the database, but there appears to be no way to determine the server from the connection object.
If I have code which is passed a connection object at runtime it would be nice to be able to see which server it's connected to without having to execute sys.dm_exec_connections (which seems like a waste of resources, and you need fairly high permissions to run it). Is there a way?
connectionobject from other code that I don't otherwise need to modify, it would be neater to just get the connection string or server from the connection.truein that code, too.