How do I turn a QueryTable Connection into an ADODB connection? - sql

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.

Related

VBA Connection String to Connect SQL server with SSL Certificate

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

How to connect to Netezza (PureData System for Analytics) via VBA

I am trying to connect to connect to Netezza using VBA. I have enabled the following:
Microsoft Excel 15.0 Object Library
Microsoft Office 15.0 Object Library
Microsoft ActiveX Data Objects 6.1 Library
Visual Basic for Applications
Here is my code:
Sub NZConn()
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim x As Variant
Set cmd = New ADODB.Command
Set RS = New ADODB.Recordset
cmd.ActiveConnection = "Driver={Netezza " & _
"ODBC};servername=servername;port=####;database=database;" & _
"username=username;password=password;"
cmd.ActiveConnection.CursorLocation = adUseClient
cmd.CommandTimeout = 120
cmd.CommandType = adCmdText
x = "Write Query here"
cmd.CommandText = x
Set rs = cmd.Execute
Sheet1.Range("A1").CopyFromRecordset rs
cmd.ActiveConnection.Close
End Sub
I can get the code to run without throwing back an error, but there is nothing that is pasted from the record set, which leads me to believe that is may have something to do with the structure of the connection string.
I have the server, user id, password, database, port, and driver.
Would I need to establish / open an ActiveConnection first?
I was able to figure out the issue on my own. I found that there is a command line builder in the 'Tools' tab in Aginity, which helped specify the exact connection string I needed to connect to Netezza. Once I had this connection string, I was getting an 'architecture mismatch' error. After downloading the 32-bit ODBC drivers for Netezza, the methodology worked perfectly. Here is the updated code below:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim iCols As Integer
Dim DB As String, User As String, PW As String, ConnectionString As String
Dim Server As String, Query As String
Dim SQLTable As Worksheet
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
Set SQLTable = Sheet1
Server = SQLTable.Cells(2,3).Value
User = SQLTable.Cells(2,4).Value
PW = SQLTable.Cells(2,5).Value
DB = SQLTable.Cells(2,6).Value
Query = SQLTable.Cells(2,7).Value
ConnectionString = "Driver={NetezzaSQL};" & _
"server=" & Server & ";" & _
"UserName=" & User & ";" & _
"Password=" & PW & ";" & _
"Database=" & DB & ";" & _
"Query Timeout=120"
cn.Open (ConnectionString)
rs.Open (Query), cn
For iCols = 0 To RS.Fields.count - 1
Worksheets("Sheet2").Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
Worksheets("Sheet2").Cells(2, "A").CopyFromRecordset rs
rs.Close
cn.Close
NB:
"IBM NETEZZA ODBC DRIVER – 32 BIT" is what I downloaded
"ODBC-DRIVER-FOR-NETEZZA-7-X86" is what showed up in my software center to install
"Name: NetezzaSQL ; Version: 7.00.04.41188 ; Company: www.ibm.com ; File: NSQLODBC.DLL" is what is shown now in my 32-bit 'ODBC Data Source Administrator' window
I think your connection string is ok, and yes you should need to open a connection first.
Like this:
AccessConnect = "Driver={Netezza " & _
"ODBC};servername=servername;port=####;database=database;" & _
"username=username;password=password;"
Dim Conn1 As New adodb.Connection
Conn1.ConnectionString = AccessConnect
Conn1.Open
then it would be
Set RS = Conn1.Execute(x) 'where x is your query

User defined function type not defined while creating connection to database

While opening database connection I get an error
User defined type not defined
I am able to create connection in same macro, but I have to create function for connection to use any were in project.
Option Explicit
Public CN As ADODB.Connection
Public Function Connection() As ADODB.Connection
If CN Is Nothing Then
Set CN = New ADODB.Connection
Dim Con_str As String
Con_str = "Provider=SQLOLEDB;Persist Security Info=True;User ID=" & getvalue("User_id") & _
";Password=" & getvalue("Password") & _
";Initial Catalog=" & getvalue("Database_Name") & _
";Data Source=" & getvalue("Server_Name") & ";"
Debug.Print Con_str
CN.Open Con_str
End
Set Connection = CN
End Function
Sub teting()
Dim rs As ADODB.Recordset
rs.Open connetion(), adOpenStatic 'CreateObject("ADODB.Connection")
ActiveSheet.range("A10").CopyFromRecordset rs
End Sub
What is the actual cause of this issue?
Thanks,
Uttam Patel
You need to enable Microsoft ActiveX Data Objects x.x Library, where x.x is replaced by the version number that you have available.
You'll find it under tools --> references in the VBA editor.

Connecting to Data Sources in the Script Task

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)

Unable to connect to SQL2005 using VBScript

Using the connection string below I can connect to a SQL2000 DB but not a SQL2005. I have the code in an ASP file.
Dim connStr, cn, rs, sql
connStr = "Provider=SQLOLEDB;Persist Security Info=True" _
& ";Initial Catalog=mydatabase" _
& ";User ID=dbuser" _
& ";Password=dbpwd" _
& ";Data Source=servername"
sql = "SELECT TOP 1 [Column1] FROM [dbo].[MyTable] order by NEWID()"
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open cn
set rs= server.CreateObject("ADODB.Recordset")
rs.CursorLocation=3
rs.Open sql,cn,3,4
if not rs.EOF then
Response.Write("<b>Column1: " & rs("Column1") & "</b><br />")
end if
set rs.ActiveConnection= nothing
rs.Close
set rs= nothing
if ucase(TypeName(cn)) = "CONNECTION" then
cn.Close
Set cn = Nothing
end if
I have even tired with SQLOLEDB.1
Sql login is enabled on the sql server.
Error: The connection cannot be used to perform this operation. It is either closed or invalid in this context.
Happens on rs.Open sql,cn,3,4
It happens to everybody sometime:
Dim connStr, cn, rs, sql
connStr = "Provider=SQLOLEDB;Persist Security Info=True" _
& ";Initial Catalog=mydatabase" _
& ";User ID=dbuser" _
& ";Password=dbpwd" _
& ";Data Source=servername"
sql = "SELECT TOP 1 [Column1] FROM [dbo].[MyTable] order by NEWID()"
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open connStr
You are calling a variable conn as connection string but you have declared and filled connStr
Change "cn.Open conn" with "cn.Open connStr"
What is the error? SQL Server 2005/8 install with remote connections disabled -- check this support article.
I see, try setting your connString on your Connection object (you use conn instead of connStr). Uee option explicit to avoid these errors.