How to secure connection between Vb6 application and mssql server? - sql-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.

Related

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

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.

VBA test connection to SQL Server

We have multiple SQL servers that our front end connects to. We need a test to check which servers are offline at any one time.
The code below works completely fine with an online SQL server but when testing an offline one takes over 30 seconds to timeout. We need this to timeout much quicker as this is a check that will be run regularly
Function ConTEST()
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim strConnect As String
strConnect = "DRIVER={SQL Server};SERVER=SERVER;UID=UID;PWD=PWD;APP=Microsoft® Windows® Operating System;DATABASE=DB_NAME"
With conn
.ConnectionString = strConnect
.CommandTimeout = 5
.ConnectionTimeout = 5
.Open
End With
End Function
Any suggestions on how to fix this timeout issue would be greatly appreciated.
if it's just a database on the server that is taken offline, then connect to the "master" database in your connection, and run the "DATABASEPROPERTYEX" function to get the status of the database you want to check.
Dim rs As New ADODB.Recordset
With conn
.ConnectionString = strConnect
.CommandTimeout = 5
.ConnectionTimeout = 5
.Open
Set rs = .Execute("select DATABASEPROPERTYEX('yourdb', 'Status') as db_status")
Debug.Print rs(0).Value
.Close
End With
if the entire server is taken offline, you may want to ping the server instead from the command line.

SQL to VBA: Error importing table from SQL into excel

In the code below, I keep getting an error message saying:
"Runtime Error '-2147467259 (80004005)': Automation Error Unspecified
Error"
The error pops up when I try and open the connection. All I want to do is import data from a local SQL DB into excel.
I don't know if it matters, but I am using SQL server 2014 express.
Sub connect()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim strConn As String
Dim connstr As String
Dim strSRV As String
Dim strDB As String
Dim sql_login As String
sqlquery = "SELECT top 10 * FROM [Source Contacts];"
connstr = "Driver={SQL Server native Client 11.0};Server=(LocalDB)\v11.0;AttachDBFileName=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SIT23DL_Validation.mdf;Database=SIT23DL_Validation;Trusted_Connection=Yes"
'Create the Connection and Recordset objects
Set conn = New ADODB.Connection
conn.ConnectionString = connstr
conn.Open
Set rs = conn.Execute(sqlquery)
If Not rs.EOF Then
'Transfer result
Sheets(1).Range("A1").CopyFromRecordset rs
'Close 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
Agreed with the comments, most likely culprit is the connection string. Try connecting to your SQL instance using 'Microsoft SQL Server Management Studio' and attach the database through that interface (not through the connection string). If all that works, you can try the following (you may need to replace localhost with your actual machine name):
connstr = "Provider=SQLOLEDB;Data Source='localhost\v11.0';Initial Catalog='SIT23DL_Validation';Integrated Security=SSPI;Trusted_Connection=Yes"

I cannot connect to the database in Visual Basic

I have the following code:
Dim string_conectare As String = "Data Source=|DataDirectory|\Database1.sdf"
Dim conexiune As SqlConnection
conexiune = New SqlConnection(string_conectare)
conexiune.Open()
If conexiune.State = ConnectionState.Open Then
MsgBox("OK")
Else
MsgBox("not ok")
End If
As you can see i would like to open a connection to the database but every time I want test it I get this error:
A network-related or instance-specific error occurred while establishing a
connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is
configured to allow remote connections. (provider: SQL Network Interfaces,
error: 26 - Error Locating Server/Instance Specified)
I struggled for more than 2 hours, so please help me!
Later edit:
I've tried this:
Dim string_conectare As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database1.sdf;Persist Security Info=True"
Dim conexiune As OleDbConnection
conexiune = New OleDbConnection(string_conectare)
conexiune.Open()
If conexiune.State = ConnectionState.Open Then
MsgBox("OK")
Else
MsgBox("not ok")
End If
but it throw me this error:
Unrecognized database format
Here is an excerpt of the same code I use to connect to my databases:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim conn As MySqlConnection
'Connect to the database using these credentials
conn = New MySqlConnection
conn.ConnectionString = "server=your server site (generally long url); user id=login id for mysql user; password=self explanatory; database=name of the DB you're trying to reach"
'Try and connect (conn.open)
Try
conn.Open()
Catch myerror As MySqlException 'If it fails do this... (i.e. no internet connection, etc.)
MsgBox("Error connecting to database. Check your internet connection.", MsgBoxStyle.Critical)
End Try
'MySQL query (where to call for information)
Dim myAdapter As New MySqlDataAdapter
'Tell where to find the file with the emails/passes stored
Dim sqlquery = "SELECT * FROM the database you selected above WHERE Email = '" & txtEmail.Text & "' AND Password = '" & txtPassword.Text & "'"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'Start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows = 0 Then
MsgBox("Invalid email address or password.", MsgBoxStyle.Critical)
Else
MsgBox("Logged in as " & txtEmail.Text & ".", MsgBoxStyle.Information)
Me.Close()
End If
End Sub
Try that.
Be sure to add the resource MySQL.Data into your project and also call it using:
Imports MySQL.Data.MySQLClient
ALSO! Be certain that when you created the database that you enabled external database access. If you don't do that then VB programs will not be able to access it and it will limit access to your webhost only.
The Jet OLEDB Provider is for Access databases. It can't handle sdf files. Try with the correct connection string.
You can take help of this website to get the correct connection string for your database:
www.ConnectionStrings.com
Is the application built on shared storage and you are trying to run it from local machine?
That could be an issue if the server containing the app does not have access to db

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