I am using VBA connection string to connect SQL server in my VB script.It was running smoothly earlier.
Recently server team installed SSL certificate in that in which my macro is not running now and stating SSL Security error as like below snapshot.
Can anyone help me to fix the issue.
Thanks in advance!!!
Regards,
I would concatenate the values required for the connection string before you open it, instead of on cnSrc.Open.
I work with VBA and use ADO to query SQL server daily and I use the following format for my connection strings:
Provider=SQLOLEDB.1;User ID=UserName;Password=Password;Data Source=SeverName;Initial Catalog=DataBaseName
You can use the code below to test:
Private Sub TestConnection()
Dim cnSrc As ADODB.Connection
Dim CONNECTION_STRING As String
Dim cnServer As String, cndb As String, cnUser As String, cnPwd As String
cnServer = "SeverName"
cndb = "DataBaseName"
cnUser = "UserName"
cnPwd = "Password"
CONNECTION_STRING = "Provider=SQLOLEDB.1;User ID=" & cnUser & ";Password=" & cnPwd & ";" & _
"Data Source=" & cnServer & ";Initial Catalog=" & cndb
On Error GoTo CleanFail
Set cnSrc = New ADODB.Connection
cnSrc.Open CONNECTION_STRING
'bit wise comparison to check the connection's state
Debug.Assert (cnSrc.State And adStateOpen) = adStateOpen 'Debug.Assert pauses execution if false
CleanExit:
'close the connection
If Not cnSrc Is Nothing Then: If (cnSrc.State And adStateOpen) = adStateOpen Then cnSrc.Close
Set cnSrc = Nothing
Exit Sub
CleanFail:
Resume CleanExit
End Sub
Related
To open, I have never written a vbs script. I have written many SQL scripts, views, developed databases. I have written plenty of VBA in Access applications.
For this, I am just trying to set up a SQL script as a VBS script, so the users don't have to go into SSMS to run it. They can just double-click the VBS script, specify the server and database when prompted, and the quick script will run for them.
This is what I have gotten so far, but I keep getting Microsoft VBScript compilation errors. The latest one is line 3 char 17, which is on a Dim statement. Just wanted to see if anyone can tell if I am missing something fundamental to this script, that is preventing it from compiling or processing correctly.
This is the very short script:
Dim conn
Set conn = createobject("Adodb.Connection")
Dim sConnString As String
Dim SqlStatement As String
sSourceServer = InputBox ("Enter the name of the SQL Server","Enter SQL Server Name","")
If Len(sSourceServer) = 0 Then
MsgBox "No SQL Server was specified.", , "Unable to Continue"
Exit Sub
End if
sSourceDB = InputBox ("Enter the name of the Law SQL Database","Enter Law SQL DB Name","")
If Len(sSourceDB) = 0 Then
MsgBox "No SQL DB was specified.", , "Unable to Continue"
Exit Sub
End if
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=" & sSourceServer & "; Initial Catalog=" & sSourceDB & "; Integrated Security=SSPI;"
MsgBox sConnString
' Open the connection and execute.
conn.Open sConnString
conn.CommandTimeout = 900
SqlStatement = "UPDATE [tablename] " & _
"SET UUID = CASE WHEN CHARINDEX('.',[Filename]) > 1 THEN LEFT(CAST([Filename] AS VARCHAR),CHARINDEX('.',[Filename])-1) ELSE [Filename] END " & _
"WHERE [Filename] IS NOT NULL"
conn.Execute(SqlStatement)
conn.Close
Set rs = Nothing
SqlStatement = vbNullString
MsgBox "All Done! Go Check your results!"
If anyone can help, I'd greatly appreciate it.
Thank you
nevermind. I kept troubleshooting and finally got it to work. For those that this might help, unlike VBA, it's easier not to declare variables as a type. just Dim them and move on. see below:
Dim conn
Set conn = createobject("Adodb.Connection")
Dim sConnString
Dim SqlStatement
StartScript
Sub StartScript()
sSourceServer = InputBox ("Enter the name of the SQL Server","Enter SQL Server Name","")
If Len(sSourceServer) = 0 Then
MsgBox "No SQL Server was specified.", , "Unable to Continue"
Exit Sub
End if
sSourceDB = InputBox ("Enter the name of the Law SQL Database","Enter Law SQL DB Name","")
If Len(sSourceDB) = 0 Then
MsgBox "No SQL DB was specified.", , "Unable to Continue"
Exit Sub
End if
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=" & sSourceServer & "; Initial Catalog=" & sSourceDB & "; Integrated Security=SSPI;"
' Open the connection and execute.
conn.Open sConnString
conn.CommandTimeout = 900
SqlStatement = "UPDATE [tablename] " & _
"SET UUID = CASE WHEN CHARINDEX('.',[Filename]) > 1 THEN LEFT(CAST([Filename] AS VARCHAR),CHARINDEX('.',[Filename])-1) ELSE [Filename] END " & _
"WHERE [Filename] IS NOT NULL"
conn.Execute(SqlStatement)
conn.Close
Set rs = Nothing
SqlStatement = vbNullString
End Sub
MsgBox "All Done! Go Check your results!"
Remember, for those looking to use this as a basis for a script - I'm not doing any checks, so if you don't know your data, this is a dangerous thing to run.
Know your data, backup your data, and if you can, add in some checks, to make sure anything that isn't a select statement, is checked and re-checked before it is run.
I have an sql database and I am able to connect with excel spreadsheet. But when I update the table from excel directly it's not updating the database and once I click refresh all the entered data is no longer in the excel table
Is it possible to update sql database from excel without using any queries?
There are many ways to do this. I'd recommend something like this, to push data from Excel to SQL Server.
Sub ButtonClick()
'TRUSTED CONNECTION
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim strFirstName, strLastName As String
Dim server, username, password, table, database As String
With Sheets("Sheet1")
server = .TextBox1.Text
table = .TextBox4.Text
database = .TextBox5.Text
If con.State <> 1 Then
con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
'con.Open
End If
'this is the TRUSTED connection string
Set rs.ActiveConnection = con
'delete all records first if checkbox checked
If .CheckBox1 Then
con.Execute "delete from tbl_demo"
End If
'set first row with records to import
'you could also just loop thru a range if you want.
intImportRow = 10
Do Until .Cells(intImportRow, 1) = ""
strFirstName = .Cells(intImportRow, 1)
strLastName = .Cells(intImportRow, 2)
'insert row into database
con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
intImportRow = intImportRow + 1
Loop
MsgBox "Done importing", vbInformation
con.Close
Set con = Nothing
End With
Exit Sub
errH:
MsgBox Err.Description
End Sub
You can also try this, which uses a Where Clause.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Excel-PC\SQLEXPRESS"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=Excel-PC\SQLEXPRESS;DATABASE=Northwind;Trusted_Connection=Yes"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
Yes, you can directly via VBA or with other tools.
via VBA (via qry)
via SSIS (https://www.simple-talk.com/sql/ssis/moving-data-from-excel-to-sql-server-10-steps-to-follow/)
via managament studio (https://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/)
via MS ACCESS (with ODBC connection to server)
...
I'm trying to update an old excel sheet that uses QueryTables to connect to a Microsoft SQL Server.
The following is working:
With ActiveSheet.QueryTables.Add(Connection:= _
"ODBC;DSN=[dbname];UID=[name];PWD=[pass];APP=Microsoft Office 2003;WSID=[machine name];DATABASE=[dbname];AutoTranslate=No;QuotedId=No;AnsiNPW=No" _
, Destination:=Range("A20"))
.CommandText = Array("[a valid query]")
There are some more sophisticated things I want to be able to do with the information this QueryTable is getting, but I keep getting the following error:
Run-time error '-2147467259 (80004005)': [DBNETLIB][ConnectionOpen (Invalid Instance()).]Invalid connection.
with the following code:
Private SqlConn As ADODB.Connection
Private Sub InitiateSqlConn(Optional User As String, Optional Pass As String, Optional Server As String, Optional DB As String)
If SqlConn Is Nothing Then
Dim strConn As String
Set SqlConn = New ADODB.Connection
If IsNull(User) Or IsEmpty(User) Or User = "" Then
User = "[user]"
End If
If IsNull(Pass) Or IsEmpty(Pass) Or Pass = "" Then
Pass = "[pass]"
End If
If IsNull(Server) Or IsEmpty(Server) Or Server = "" Then
Server = "[ServerName]"
End If
If IsNull(DB) Or IsEmpty(DB) Or DB = "" Then
DB = "[DBName]"
End If
strConn = "Provider=SQLOLEDB;Data Source=" & Server & ";Initial Catalog=" & DB & ";"
SqlConn.Open "Provider=SQLOLEDB;Data Source=[SeverName];Initial Catalog=[DBName];Trusted_connection=yes;", "[User]", "[Pass]"
End If
End Sub
Public Sub QueryInto(QR As String, ByRef RS As ADODB.Recordset, Optional User As String, Optional Pass As String, Optional Server As String, Optional DB As String)
InitiateSqlCon User, Pass, Server, DB
RS.Open QR, SqlConn
End Sub
I have also tried:
SqlConn.Open "Driver={SQL Server};Server=[SeverName];Database=[DBName];UID=[User];PWD=[Pass];"
And I get the following error:
Run-time error '-2147467259 (80004005)': [Microsoft][ODBC SQL Server Driver][DBNETLIB]Invalid connection.
Errors always occur on SqlConn.Open.
How do I get the connection that is established with the QueryTable to be established as an ADODB.Connection object ?
This one will fail because you are appending extra text after the "Trusted_connection" parameter. If you use a trusted connection, you don't need a username or password, and the syntax is different for SQLOLEDB than with {SQLServer} (it should be Integrated Security=SSPI;.
SqlConn.Open "Provider=SQLOLEDB;Data Source=[SeverName];Initial Catalog=[DBName];Trusted_connection=yes;", "[User]", "[Pass]"
You also need to build the Data Source and Initial Catalog into the string instead of Data Source=[SeverName] and Initial Catalog=[DBName].
This one will fail because you aren't using any security parameters:
strConn = "Provider=SQLOLEDB;Data Source=" & Server & ";Initial Catalog=" & DB & ";"
This one fails because for the same reason as the first. You need to build the actual parameters into the connection string.
SqlConn.Open "Driver={SQL Server};Server=[SeverName];Database=[DBName];UID=[User];PWD=[Pass];"
It should look something more like this:
Private Sub InitiateSqlConn(Optional User As String, Optional Pass As String)
If SqlConn Is Nothing Then
Dim strConn As String
Dim Server As String
Dim DB As String
'These can't be optional. They are required.
Server = "TheActualNameOfTheServerHere"
DB = "TheActualNameOfTheDatabaseHere"
Set SqlConn = New ADODB.Connection
If User = vbNullString Or Pass = vbNullString Then
'No credentials. Try a trusted connection.
strConn = "Provider=SQLOLEDB;Data Source=" & Server & _
";Initial Catalog=" & DB & ";Integrated Security=SSPI;"
Else
'Credentials.
strConn = "Provider=SQLOLEDB;Data Source=" & Server & _
";Initial Catalog=" & DB & ";User Id=" & User & _
"; Password=" & Pass & ";"
End If
SqlConn.Open strConn
End If
End Sub
Note that the Server and DB parameter cannot be optional. They are in fact required and must be valid in order to connect. You can also skip the null and empty checks for optional string parameters unless you're doing something really strange. They will default to vbNullString if nothing is passed.
I'm having some trouble using the connection manager from a script task in SSIS. The program will compile perfectly until I try using the connection that is set in the Environment.
Private Sub InsertLog(ByRef log() As String)
Dim conn As SqlClient.SqlConnection
conn = _
DirectCast(Dts.Connections("ConfigDB").AcquireConnection(Dts.Transaction), _
SqlClient.SqlConnection)
MsgBox(log(0) & " " & log(1) & " " & log(2) & " " & log(3) & Dts.Connections("ConfigDB").ConnectionString.ToString())
End Sub
If I comment out the Dim and DirectCast the package executes successfully and I can successfully get the connection string in a messagebox.
Data Source=PathToServer;Initial Catalog=DB;Provider=...;Integrated Security=...;Application Name=...;Auto Translate=False;
Has anyone else had this happen?
I have a solution. The reason why it failed was because of the Provider and Auto Translate, so my solution is to strip out what is not needed.
Dim strConnection As String = Dts.Connections("Automation").ConnectionString.ToString()
Dim regProvider As New Regex("Provider=([^;]*);")
Dim regTranslate As New Regex("Auto Translate=([^;]*);")
strConnection = regProvider.Replace(strConnection, "")
strConnection = regTranslate.Replace(strConnection, "")
Dim conn As New SqlClient.SqlConnection(strConnection)
I have an ADODB connection in VBA for connecting to an SQLServer database. I want to catch the error that is raised when connection.Open is called and the given database is unreachable.
My code looks like this:
Public Function Connect() As Boolean
On Error GoTo DBError
Dim dbServer As String
Dim dbName As String
Dim dbUser As String
Dim dbPwd As String
dbServer = DatabaseSettings.dbServer
dbName = DatabaseSettings.dbName
dbUser = DatabaseSettings.dbUser
dbPwd = DatabaseSettings.dbPwd
Dim connectionString As String
connectionString = "Server=" & dbServer & ";Database=" & dbName & ";User Id=" & dbUser & ";Password=" & dbPwd
Set conn = New ADODB.Connection
conn.Provider = "sqloledb"
With conn
.ConnectionTimeout = 2
.CursorLocation = adUseClient
.Open connectionString
.CommandTimeout = 0
End With
Connect = True
Exit Function
DBError:
Connect = False
End Function
My problem is that when i try to run this code with an incorrect connectionString an error is raised and shown in a MsgBox and not caught by the "On Error GoTo DBError".
Is there something wrong in my error handling code or do i need to find another way of catching this error?
Thank you for your help. Any suggestions are welcome.
Not sure if this is it, but in the VBE window make sure the Tools...Options...General...Error Trapping option is set to "Break on Unhandled Errors". If it were set to "Break on All Errors" this may bypass your handlers.
Try to use the below, worked here:
With conn
.ConnectionTimeout = 2
.CursorLocation = adUseClient
.ConnectionString = connectionString
.Open
.CommandTimeout = 0
End With