how to connect VBScript (Excel) to SQL Server web database (via IP) - sql-server

I'm at my job trying to do some unknow stuff for me, you see, we're trying to connect an excel document with a VBScript Macro to a databse stored in web server but for some reason doesn't recognizes the user and throws an error repeatedly, i discarded a connection issue since it returns an SQL error instead of something like a timeout or server doesn't exists or something like that, we're trying to connect to the server using the ip address, we also checked that the logging method is on mixed (win and sql) and remotes connections to the server are enabled as well, also if i use the credentials provided in the connection string (username and password) i can actually log in to SQL Server without any issue, we also tried a direct connection (external vpn) because we thought it could be our firewall, but got the same error anyway, so we have no clue what it could be and we're kinda running out of ideas on how to do this, i'll post down below the code i'm using to trying the connection (obviously test data but similar to reality)
picture of the error i'm getting (don't post the original since it's in spanish but is very similar to this):
code i'm currently trying:
Sub excel_sqlsrv()
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
strConn = "Driver={ODBC Driver 17 for SQL Server};Server=10.20.30.5;Database=mydb;UID=sa;PWD=abcd12345;"
conn.Open strConn
strSqL = "SELECT * FROM USERS"
rs.Open strSqL
End Sub
Any advice, tip or trick could be of tremendous help for me, i'll be looking forward to any kind of comment, thanks in advance

Use the ODBC Data Source Administrator to create a connection named mydb and test it works. Then use
Sub excel_sqlsrv()
Const strConn = "mydb" ' ODBC source
Const strsql = "SELECT * FROM USERS"
Dim conn As Object, rs As Object
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
On Error Resume Next
conn.Open strConn
If conn.Errors.Count > 0 Then
Dim i, s
For i = 0 To conn.Errors.Count - 1
s = s & conn.Errors(i) & vbLf
Next
MsgBox s
Else
On Error GoTo 0
Set rs = conn.Execute(strsql)
Sheet1.Range("A1").CopyFromRecordset rs
End If
End Sub

You can try using OLEDB provider instead of ADODB.

Related

Using VB6 with ADO to access a MS SQLServer 2019 linked server

Note that both databases are MS SQL Server.
The SELECT works fine and the code doesn't break until it gets to ADODB.Recordset.Update. The SQL account has all of the necessary permissions. The table [NASMSPAINT].[Ignition].[dbo].[booth_Styles] is a linked server. The User account I am using has enough permissions because I am able to UPDATE the table using Python. This is on a secure isolated network so security is of very little concern, this just needs to work using VB6 with ADO. Long story short, this code is part of a large application still using VB6 and rewriting the code in Visual Studio is not an option.
Using ADODB.Recordset.OPEN using adLockOptimistic option, the following error occurs on the ".Update" line of the code:
SQL server error message 16964 - for the optimistic cursor, timestamp columns are required if the update or delete targets are remote.
Using ADODB.Recordset.OPEN using adLockPessimistic option, the following error occurs on the ".Update" line of the code:
SQL Server Error Msg 16963 – You cannot specify scroll locking on a cursor that contains a remote table.
I have found very little information on the internet concerning these errors. I have set the following server option properties on the linked server on the database:
Collation Compatible: TRUE
Data Access:TRUE
RPC:TRUE
RPC Out:TRUE
Use Remote Collation:FALSE
Collation Name:
Connection Timeout:0
Query Timeout:0
Distributor:FALSE
Publisher:FALSE
Subscriber:FALSE
Lazy Schema Validation:FALSE
Enable Promotion of Distributed Transaction:TRUE
VB6 code:
sDBName = "PROVIDER=SQLOLEDB.1;Data Source=192.168.2.70;User ID=xxxx;Password=xxxx;Persist Security Info=False"
Dim Conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set Conn = New ADODB.Connection
Conn.Open sDBName
Set rs = New ADODB.Recordset
With rs
.Open "SELECT * FROM [NASMSPAINT].[Ignition].[dbo].[booth_Styles] WHERE [Booth] = 'AdPro' ORDER BY [StyleID]", Conn, adOpenDynamic, adLockOptimistic
.MoveFirst
nThisStyle = 1
Do Until .EOF
![Plant_Number] = Style_Data(nThisStyle).PlantStyle
![Style_Number] = Style_Data(nThisStyle).FanucStyle
![Descript] = Style_Data(nThisStyle).StyleDesc
![Robots_Required] = Style_Data(nThisStyle).StyleRobotsReq
.Update
.MoveNext
nThisStyle = nThisStyle + 1
Loop
End With
The code breaks on the .Update line.

How to secure connection between Vb6 application and mssql server?

I am working on a legacy application which uses sqloledb provider and activex data objects to connect to mssql database. Now I need to encrypt the connection between the application and server without force encryption option in sql server.
I have installed a self signed certificate in the sql server instance and tried putting the Encrypt=true and Trustservercertificate=true in connection string. But the connection is not encrypted.
I have tried using ODBC provider with ADO and while using encrypt=true and trustservercertificate=true, I am getting a SSL security error which opening the connection.
Please let me know how to establish a secure connection using ADO 2.8 library.
Private Sub Command1_Click()
Dim sConnectionString As String
Dim strSQLStmt As String
'-- Build the connection string
'sConnectionString = "UID=userid;PWD=password;Initial Catalog=EHSC_SYM_Kings_Development;Server=EHILP-257\MIB14;Provider=MSOLEDBSQL;Encrypt=YES;trustServerCertificate=YES"
'sConnectionString = "Provider=sqloledb;Data Source=192.168.27.91\MIB14;Initial Catalog=EHSC_SYM_Kings_Development;User Id=userid;Password=password;Encrypt=YES;trustServerCertificate=YES"
'sConnectionString = "driver={SQL Server};server=192.168.27.91\MIB14;user id=userid;password=password;Initial Catalog=EHSC_SYM_Kings_Development;Encrypt=Yes;trustServerCertificate=True"
sConnectionString = "Provider=SQLNCLI11;Server=192.168.27.91\MIB14;Database=EHSC_SYM_Kings_Development;Uid=userid;Pwd=password;Encrypt=yes;trustServerCertificate=True"
strSQLStmt = "select * from dbo.patient where pat_pid = '1001'"
'DB WORK
Dim db As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim result As String
db.ConnectionString = sConnectionString
db.Open 'open connection
With cmd
.ActiveConnection = db
.CommandText = strSQLStmt
.CommandType = adCmdText
End With
With rs
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmd
End With
If rs.EOF = False Then
rs.MoveFirst
Let result = rs.Fields(0)
End If
'close conns
rs.Close
db.Close
Set db = Nothing
Set cmd = Nothing
Set rs = Nothing
End Sub
Thank you all for your suggestions, I finally managed to make the connection secure by changing the driver to sqlserver native client 11(ODBC). Looks like sqloledb doesn't have support for tls. Changing the driver to ODBC doesn't seem to change the behaviour much. Rest of my code works fine without any changes
sConnectionString = "Driver={SQL Server Native Client 11.0};Server=192.168.27.91\MIB14;Database=xxxxxxxx;user id=xxxxxxx;password=xxxxxxxxx;Encrypt=yes;TrustServerCertificate=yes"
Just went through this myself.
For your original connection string the keyword you're looking for is not "Encrypt=true" or "Encrypt=yes" like most of the internet would lead you to believe. It's "Use Encryption for Data=true".
So your connection string becomes:
sConnectionString = "Provider=SQLNCLI11;Server=192.168.27.91\MIB14;Database=EHSC_SYM_Kings_Development;Uid=userid;Pwd=password;Use Encryption for Data=true;trustServerCertificate=True"
The trustservercertificate=true is just for testing with self-signed certs... and exposing yourself to man-in-the-middle attacks ;)
For reference this was tested with:
VB6 connecting to SQL Server 2016 using SQLNCLI11 provider via ADODB.

Catching error message from SQL Server in VBA in Excel

I am doing an excel macro in order to automate some query what eventually I run in SQL Server. My problem is that I don't know how the server could alert excel if a query did not succeed.
For example, I am importing a file, and there is no syntax error, but it might result in error if bulk insert statement is not set properly. For the SQL connection I use the following:
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=localhost;" & _
"Initial Catalog=" & MyDatabase & ";" & _
"Integrated Security=SSPI;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
Set rs = conn.Execute(Myquery)
If I have a syntax error while compiling the code it stops which is good. But if I have another problem, e. g. the database name is not good, the table already exists, then the program runs with no error, I only can detect when I check it in SQL Server. I really want to know somehow whether the query run has resulted in error and then code some alerting message then into my macro. How can I do that?
Every help is much appreciated!
The ADO connection object has an Errors collection, which you can check after running your SQL:
conn.Errors.Clear
Set rs = conn.Execute(Myquery)
If conn.Errors.Count > 0 Then
For i = 0 To conn.Errors.Count
Debug.Print conn.Error(i).Number
Debug.Print conn.Error(i).Source
Debug.Print conn.Error(i).Description
next i
End If
That should get you started. You may find that you're seeing an 'error zero' that's actually a status message; if so, you'll have some additional coding to to do.
I found this helpful but needed to use:
Debug.Print conn.Errors.Item(i).Description
Debug.Print conn.Errors.Item(i).Source
Debug.Print conn.Errors.Item(i).NativeError
I might be using a different connection type

How do I connect to SQL Server with VB?

I'm trying to connect to a SQL server from VB. The SQL server is across the network uses my windows login for authentication.
I can access the server using the following python code:
import odbc
conn = odbc.odbc('SignInspection')
c = conn.cursor()
c.execute("SELECT * FROM list_domain")
c.fetchone()
This code works fine, returning the first result of the SELECT. However, I've been trying to use the SqlClient.SqlConnection in VB, and it fails to connect. I've tried several different connection strings but this is the current code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As New SqlClient.SqlConnection
conn.ConnectionString = "data source=signinspection;initial catalog=signinspection;integrated security=SSPI"
Try
conn.Open()
MessageBox.Show("Sweet Success")
''#Insert some code here, woo
Catch ex As Exception
MessageBox.Show("Failed to connect to data source.")
MessageBox.Show(ex.ToString())
Finally
conn.Close()
End Try
End Sub
It fails miserably, and it gives me an error that says "A network-related or instance-specific error occurred... (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I'm fairly certain it's my connection string, but nothing I've found has given me any solid examples (server=mySQLServer is not a solid example) of what I need to use.
Thanks!
-Wayne
You are using an ODBC DSN as a SqlClient server name. This is not going to work. You have to use a SqlClient connection string, and for SqlClient the DataSource property is the server name or a SQL Native Client server alias (which is not the same as an ODBC DSN).
Replace signinspection with the actual name of your SQL Server host. If is a named instance or listening on a non default port, you have to specify that too, eg: hostname\instancename
Check out connectionstrings.com for samples. It looks like in your python example, you are accessing the DB via ODBC.
The string you are using is connecting with the built in .NET SQL Server DB provider, so you need to use an ODBC connection string OR change your data source to the actual server name (if no other instances) or servername/instance name.
Sure your Server and Database have the same name?
Here you have a link that would allow you to generate a connection string and test it
http://blogs.msdn.com/dhejo_vanissery/archive/2007/09/07/One-minute-Connection-string.aspx.
Well, I went ahead and used an ODBC Connection. It appears that that is what I was wanting in the first place.
In order to do use the ODBC I had to go to http://support.microsoft.com/kb/310985 and install a few files. Following the directions I came up with the following code that seems to work just fine:
Dim conn As OdbcConnection
conn = New OdbcConnection("DSN=SignInspection")
Dim mystring as String = "SELECT * FROM list_domain"
Dim cmd As OdbcCommand = New OdbcCommand(mystring, conn)
Dim reader As OdbcDataReader
Dim columnCount As Integer
Dim output As String
Dim data as Object() = New Object(10) {}
conn.Open()
MsgBox("Connected!")
reader = cmd.ExecuteReader()
While reader.Read()
columnCount = reader.GetValues(data)
output = ""
For i As Integer = 0 To columnCount - 1
output = output & " " & data(i).ToString()
Next
Debug.WriteLine(output)
End While
conn.Close()
Of course I'll have it cleaned up a lot, but I figure maybe someone will end up looking for the same solution, and maybe they'll see my code before they spend too much time.
ed. columsCount -> columCount
You might want to take a look on Microsoft Enterprise Library Data Access Application Block in order to make it easier to connect and to support multiple underlying datastores.
Good success! =)

Requested operation requires an OLE DB Session object... - Connecting Excel to SQL server via ADO

I'm attempting to take Excel 2003 and connect it to SQL Server 2000 to run a few dynamicly generated SQL Queries which ultimately filling certain cells.
I'm attempting to do this via VBA via ADO (I've tried 2.8 to 2.0) but I'm getting an error while setting the ActiveConnection variable which is inside the ADODB.Connection object. I need to resolve this pretty quick...
Requested operation requires an OLE DB Session object, which is not supported by the current provider.
I'm honestly not sure what this error means and right now I don't care. How can get this connection to succeed so that I can run my queries?
Here is my VB code:
Dim SQL As String, RetValue As String
SQL = " select top 1 DateTimeValue from SrcTable where x='value' " 'Not the real SQL
RetValue = ""
Dim RS As ADODB.Recordset
Dim Con As New ADODB.Connection
Dim Cmd As New ADODB.Command
Con.ConnectionString = "Provider=sqloledb;DRIVER=SQL Server;Data Source=Server\Instance;Initial Catalog=MyDB_DC;User Id=<UserName>;Password=<Password>;"
Con.CommandTimeout = (60 * 30)
Set Cmd.ActiveConnection = Con ''Error occurs here.
' I'm not sure if the rest is right. I've just coded it. Can't get past the line above.
Cmd.CommandText = SQL
Cmd.CommandType = adCmdText
Con.Open
Set RS = Cmd.Execute()
If Not RS.EOF Then
RetValue = RS(0).Value
Debug.Print "RetValue is: " & RetValue
End If
Con.Close
I imagine something is wrong with the connection string but I've tried over a dozen variations. Now I'm just shooting in the dark....
Note/Update: To make matters more confusing, if I Google for the error quote above, I get a lot of hits back but nothing seems relevant or I'm not sure what information is relevant....
I've got the VBA code in "Sheet1" under "Microsoft Excel Objects." I've done this before but usually put things in a module. Could this make a difference?
You have not opened your connection yet. I think you need a Con.Open before you assign it to the Command object.
Con.ConnectionString = "Provider=sqloledb;DRIVER=SQL Server;Data Source=Server\Instance;Initial Catalog=MyDB_DC;User Id=<UserName>;Password=<Password>;"
Con.CommandTimeout = (60 * 30)
Con.Open
Set Cmd.ActiveConnection = Con 'Error occurs here.
Cmd.CommandText = SQL
Cmd.CommandType = adCmdText

Resources