In my program I want connect to SQL Server using ADODB.Connection, then read the data using ADODB.RecordSet, and use Index and Seek to find the searched record.
I tried using this connection string Provider=SQLNCLI11;;Data Source=localhost;Initial Catalog=TestDB;Integrated Security=SSPI;Persist Security Info=False;, adOpenDynamic as cursorType, adLockOptimistic as LockType and adCmdTable as CommandType.
But when I try to call the Supports method on recordset with adSeek or adIndex returns false.
There is a way to connect to SQL Server and open a Recordset with support for seek and index?
Edit here the code:
LOCAL oCn, nCursor, nLock,oRS
oCn := CreateObject( "ADODB.Connection" )
oCn:ConnectionString := "Provider=SQLNCLI11;;Data Source=localhost;Initial Catalog=TLPosWin;Integrated Security=SSPI;Persist Security Info=False;"
oRS := CreateObject( "ADODB.RecordSet" )
nCursor := adOpenDynamic
nLock := adLockOptimistic
oRS:CursorLocation := adUseServer
oRS:Open("Articoli",oCn, nCursor, nLock, adCmdTable)
? "seek",oRS:Supports(0x200000),"index",oRS:Supports(0x100000) //both false
oRS:Index := "Articoli_ARTART" //Error
oRS:Seek('=',1,'000611') //Error
Related
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.
I have a .vbs script that runs the following sql query:
Select COUNT (*) from sys.objects
Which count the rows, from the sql query output:
https://i.stack.imgur.com/wduXW.png[1]
And if there is any rows found (> 0). genereate an alert in SCOM using the PropertyBag scripting runtime in SCOM.
Problem is,
When debugging the script (using cscript), i get the following error messeage:
(11,1) Microsoft OLE DB Provider for ODBC Drivers:
[Microsoft][ODBC SQL Server Driver][Shared Memory]SQL Server does not exist or access denied.
Although the Connection string seems to be correct:
strConnection = "Driver={SQL Server};Server=SCOMSRVDB01;Database=DBABee;Trusted_Connection=TRUE"
Here is the Full VBScript:
Dim objCN, strConnection
Dim oAPI, oBag
Set objCN = CreateObject("ADODB.Connection")
Set oAPI = CreateObject("MOM.ScriptAPI")
Set oBag = oAPI.CreatePropertyBag()
strConnection = "Driver={SQL Server};Server=SCOMSRVDB01;Database=DBABee;Trusted_Connection=TRUE"
objCN.Open strConnection
Dim strSQLQuery
strSQLQuery = "Select COUNT (*) from sys.objects"
Dim objRS
Set objRS=CreateObject("ADODB.Recordset")
Set objRS = objCN.Execute(strSQLQuery)
Do Until objRS.EOF
'WScript.Echo objRS.Fields("No column name")
if objRS.Fields("No column name") > 0 then
'WScript.Echo "evaluated as bad"
Call oBag.AddValue("State","BAD")
Call objAPI.Return(oBag)
else
Call oBag.AddValue("State","GOOD")
Call objAPI.Return(oBag)
end if
objRS.MoveNext
Loop
objRS.Close
It worth mentioning,
That in our company you can't connect to an sql server without mention Port Number.
But when i tried to add it (Port: 2880) in the connection string:
strConnection = "Driver={SQL Server};Server=SCOMSRVDB01,2880;Database=DBABee;Trusted_Connection=TRUE"
The script returen the following error:
(23,17) ADODB.Recordset: Item cannot be found in the collection corresponding to the requested name or ordinal.
The ADODB error indicating that the item connect be found means that you successfully connected to the DB, and it can't find the column you requested. This is what is can't find: objRS.Fields("No column name")
Change your query and name the column:
strSQLQuery = "Select COUNT (*) as countStuff from sys.objects"
Then change what you are looking for:
if objRS.Fields("countStuff") > 0 then
My department uses an application created using VBA and Access 2016. It originally pointed to an Access database on one of our servers. After migrating the data to a different server, I now need it pointing to the other SQL Server database on that different server. But I can't seem to make the connection.
I have dbowner permissions on the server in question.
The original code for connection string was as follows:
'Remove the filter, close the log on form, and open the Switchboard
rst.Filter = 0
DoCmd.Close acForm, "frmUserLogOn"
'Open the Main Switchboard
DoCmd.OpenForm "frmMain", acNormal
'Open the InactiveShutDown form in Hidden mode
DoCmd.OpenForm "frmInactiveShutDown", acNormal, , , , acHidden
...
Set conn = CurrentProject.Connection
...
rstLog.Open "tblUserLog", conn, adOpenKeyset, adLockOptimistic
rstLog.AddNew
rstLog!UserID = rst!UserID
rstLog!TimeIn = Now()
rstLog.Update
My new code is as follows:
'DoCmd.OpenForm "frmInactiveShutDown", acNormal, , , , acHidden
'Commented out the above statement
...
'Set conn = CurrentProject.Connection
'==================================================================
'Start of Added Code for SQL Migration
Set conn = New ADODB.Connection
With conn
.ConnectionString = "Provider=SQLNCLI11;Data Source=(My Server Name);Initial Catalog=(My Database Name);User ID=(Username);Password=(Password)"
.Open
If .State = adStateClosed Then
MsgBox "Connection unsuccessful. Could not open connection.", vbInformation, "Error:"
End If
End With
Set rst = New ADODB.Recordset
With rst
.ActiveConnection = conn
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockOptimistic
.Open "tbl_Users"
End With
'End of Added Code for SQL Migration - See Section 2 for rest of code.
'==================================================================
...
'Section 2 of Code
'==================================================================
'Start of added code for SQL Migration
rstLog.Open "tblUserLog", conn, adOpenStatic, adLockOptimistic
rstLog.AddNew
rstLog!UserID = rst!UserID
rstLog!TimeIn = DateTime.Now()
rstLog.Update
MsgBox "Success! Connection was made successfully.", vbInformation
'End of added code for SQL Migration
'===================================================================
My form has a drop down to select list of users form a table. I added a test user in that table but that test user doesn't show up in the drop down list. Hence, I think the connection is not being made.
Do I have to enter the names for Data Source, Initial Catalog, User ID and Password in quotes? So UserID='Admin'; Password='Test'?
Anyone know what I'm doing wrong?
Basically, you have a version confusion of same named table between local Access frontend database and backend SQL Server database. Currently, your code updates the tblUserLog on the SQL Server backend side and is not the same tblUserLog on the Access frontend side which likely is the one bound to your form. Hence, why you cannot see any update as the server table is never shown.
Simply do one of two things:
Use SQL Server Version: Delete or archive the Access' version and add tblUserLog as an ODBC linked table. Be sure to remove the dbo_ or other schema prefix and keep same name tblUserLog. And since table names do not change, everything such as forms and VBA code should not need to change.
Use Access Version: Keep the local Access table, tblUserLog, and update this one in VBA which requires adding another connection object and running a recordset update on that connection. See below with prefixes of server_ and local_ on ADO objects:
' OPEN SERVER CONNECTION AND SERVER TABLE RECORDSET
Set server_conn = New ADODB.Connection
With server_conn
.ConnectionString = "Provider=SQLNCLI11;Data Source=(My Server Name);Initial Catalog=(My Database Name);User ID=(Username);Password=(Password)"
.Open
If .State = adStateClosed Then
MsgBox "Connection unsuccessful. Could not open connection.", vbInformation, "Error:"
End If
End With
Set server_rst = New ADODB.Recordset
With server_rst
.ActiveConnection = conn
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockOptimistic
.Open "tbl_Users"
End With
' OPEN LOCAL CONNECTION AND UPDATE LOCAL TABLE RECORDSET
Set local_conn = CurrentProject.Connection
Set local_rstLog = New ADODB.Recordset
local_rstLog.Open "tblUserLog", local_conn, adOpenStatic, adLockOptimistic
local_rstLog.AddNew
local_rstLog!UserID = server_rst!UserID ' NOTICE SERVER DATA USED HERE
local_rstLog!TimeIn = DateTime.Now()
local_rstLog.Update
...
' RELEASE RESOURCES
Set server_rst = Nothing: Set local_rstLog = Nothing
Set server_conn = Nothing: Set local_conn = Nothing
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
I have the following VBScript, which is supposed to connect to a SQL Server 2005 database. But, my connection is failing. Why?
Set dbConnection = CreateObject("ADODB.Connection")
dbConnString = "Provider=SQLOLEDB.1;Data Source=srv\test1;" & _
"Initial Catalog=tset_DB;user id ='abc';password='abc'"
'Open the connection
dbConnection.Open dbConnString
You don't need quotations around your username and password. Try this:
Set dbConnection = CreateObject("ADODB.Connection")
dbConnString = "Provider=SQLOLEDB.1;Data Source=srv\test1;" & _
"Initial Catalog=test_DB;user id =abc;password=abc"
'Open the connection
dbConnection.Open dbConnString
Also, your Initial Catalog was set to tset_DB, when I'm guessing it should be test_DB.
ConnectionStrings.com is a huge help for ensuring that your connection strings are valid.