How to solve this error SQL Server Network Interfaces: Connection string is not valid [87] - sql

I am trying to connect sql server with vba using the code from a youtube tutorial video (https://www.youtube.com/watch?v=OWKae1pTTnE), but when i run the code to check if it works, I had an error openning the connections, Can you help me please? I have already install sql server 2019 and I have SQL Server Management Studio 18.
error: SQL Server Network Interfaces: Connection string is not valid [87]
Here is the code:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=MSOLEDBSQL;" & _
"Server=MyServer\MSSQLSERVER;" & _
"Database=master;" & _
"Trusted_Connection=yes;"
cn.Open 'The error occurs here
cn.Close

The solution that help wiht the issue above was provided by #Nick.McDermaid:
My error was in the Connection string, visiting the link:[1]: https://social.technet.microsoft.com/wiki/contents/articles/1409.how-to-create-a-sql-connection-string-for-an-application-udl-file.aspx?Redirected=true
It shows a simple steps to do the string conection based on the conditions that are needed. Once you follow the steps that and use it, works fine! In my case the solution looks like this:
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=SQLOLEDB.1;
Integrated Security=SSPI;
Persist Security Info=False;
Initial Catalog=MyDataBaseName;
Data Source=MyServer"
cn.Open 'The error that was here disappiers and runs fine'
cn.Close

Related

Unable to connect to DB from VBA but able to connect from Access

I'm able to connect to a database using Access, but not from VBA. In Access, I use the server name, Windows NT Integrated Security,and the database name. In VBA, I've tried many variations of variable names and values in the connection string, and the db.Open command always fails. I generally get an error about not being able to find an installable ISAM, or Multiple-step OLE DB operation generated errors. Is there a way to determine what I can use as a connection string from the working Access connection? One example of code that fails with the latter error:
Dim db As Object
Dim adoRS As Object
Set db = CreateObject("ADODB.Connection")
Set adoRS = CreateObject("ADODB.recordset")
db.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Server=sql03;" & _
"Database=db1;" & _
"Integrated Security=SSPI;"
The provider you as using in the connection string is for MS Access.
If thats the correct database then do the following.
Add the refrence "Microsoft Office 14.0 Access Database Engine object library.
Dim cnString, query As String
Dim rs As New ADODB.Recordset
'If older version of MS access then try Provider=Microsoft.Jet.OLEDB.4.0;'
cnSTring= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<Path>;Jet OLEDB:Database Password=<Pass>;"
query = "SELECT * FROM TABLE"
rs.Open query, cnString, adOpenStatic, adLockOptimistic

OLEDB Connection from Excel to Oracle Issue

Everyone,
A VBA problem has been killing me the past two days. I have a Macro Based Model in Excel that has data sets bought into the spreadsheets from Oracle via OLEDB. To illustrate the problem simply I have created two functions within the Model. One using ODBC("odbc") and another using OLEDB("OraOLEDB"). The code was working completely fine last week and it has not been changed.
Now, however I get an error message that states "Run-Time Error '424': Object Required when I execute the line "conn.Open strCon" in sub "OraOLEDB".A connection can't be established with the database! So when I am trying to establish a connection to the database with that line of code, it fails. What is interesting is that via ODBC, a connection can be established. The line "conn.Open strCon" in sub "odbc" executes successfully and I am able to establish a connection to the database.
I did not change anything in the Excel Model but I did have a bunch of windows updates recently. I don't know if that corrupted anything. I think it may have. The reason why I don't want to use the ODBC connection is that it is significantly slower. I get run times 10x faster using OLEDB. Please let me know if you can help.
Sub odbc()
Dim conn As Object
Dim strCon As String
strCon = "Driver={Microsoft ODBC for Oracle};
CONNECTSTRING=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=xxx)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=xxx)));
uid=xxx;pwd=xxx;"
Set conn = CreateObject("ADODB.Connection")
conn.Open strCon
End Sub
Sub OraOLEDB()
Dim conn As Object
Dim strCon As String
strCon = "Provider=OraOLEDB.Oracle;
Data Source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)
(HOST = xxx)(PORT = 1521))
(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = xxx)));
User Id=xxx;Password=xxx"
Set conn = CreateObject("ADODB.Connection")
conn.Open strCon
I see the host for the OLEDB connection is modn-ast-fdb1. ... while for the ODBC connection you have modn-ast-tdb1. ... Shouldn't the host be the same?
This means Set conn = CreateObject("ADODB.Connection") returns nothing. Check ADODB.dll registration. Alternatively you may use
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
and you'll see if ADODB is available at the moment you edit the script not waiting for runtime errors.

VBA Execute Access Query error: database or object read only

I have tried executing this code:
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim strConn As String
Dim strAcc As String
'Connecting to the DB
cn.ConnectionTimeout = 7200
cn.CommandTimeout = 7200
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\Documents\proof.accdb;Mode=Share Deny None; Persist Security Info=False"
cn.Open strConn
'Creating the query string
strAcc = "SELECT * " _
& " INTO Table1 " _
& " FROM [Excel 8.0;HDR=YES;DATABASE=D:\Documents\database.xlsm].[Sheet1$];"
'Executing the query
rs.Open strAcc, cn, adOpenDynamic
When executing it gets the error: "Can't refresh. Database or object read only" on the line:
rs.Open strAcc, cn, adOpenDynamic
I don't know how to fix this problem. Curious thing is that when executing a different query (selecting from an existing table) it works perfectly. That's why I guess the problem is related to the fact that a new table is being created with the SELECT INTO command. I also tried writing "Mode=Share Deny None" (as you may see) in the connection but didn't solve the problem.
Your having this issue most likely because the directory the back end database Located at: "d:\Documents\proof.accdb" is sitting within a directory you do not have Write Permissions to. Thus you are only able to read from the DB/ File and not "Write" i.e. perform INSERTS or UPDATES Like you are currently trying to do.
Navigate to and right click that directory, Select "Properties". Looking at the Security tab assign yourself permissions to that directory if you are able to.

Using Excel VBA to run SQL query

I am fairly new to SQL and VBA. I have written a SQL query that I would like to be able to call and run from a VBA sub in an excel workbook and then bring the query results into the workbook. I have found some subs online (stackoverflow and other places) that claim to do this but I am having trouble understanding them as they contain no explanation. For example, here is a sub that I found online:
Sub ConnectSqlServer()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _
"Initial Catalog=MyDatabaseName;" & _
"Integrated Security=SSPI;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM Table1;")
' Check we have data.
If Not rs.EOF Then
' Transfer result.
Sheets(1).Range("A1").CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
First of all, would this work? Second, what do I need to replace in the sub (it looks like provider, data source, initial catalog, etc) and where do I find the info to replace them with?
I hope this question is not too confusing and I appreciate your help!
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Trying to connect to sql server 2012 from within Excel using ADODB connection

I have some code written in VBA. I need to query a table in a sql server 2012. I cannot get the connection to work. Below is what I have tried so far without any luck.
The error message I get is "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done."
Dim cn As New ADODB.Connection
Dim cnString As String
cnString = "Provider=SQLOLEDB.1;" & _
"Server=MyServerName;" & _
"Initial Catalog=MyDatabaseName;" & _
"Integrated Security=False;"
cn.Open cnString, "myID", "myPassowrd"