Connect Oracle SQL to VBA - vba

I am able to connect Python to my Oracle SQL DB on a Windows computer, but strangely enough I cannot seem to get it working from VBA.
For reference, this is the Python Code to connect:
cx_Oracle.connect(f'{self.user}/{self.pwd}#//{self.host}:{self.port}/{self.service_name}')
I have tried replicating this similar structure in my VBA code, but I get an error message. Here is the code I've been using:
Sub CallDB_Return_Flexible(stSQL As String, rstStart As Range)
Dim sqlConn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim rtn As Boolean
Dim cmd As New ADODB.Command
Dim cs As String
'On Error Resume Next
Set sqlConn = New ADODB.Connection
cs = "Provider=OraOLEDB.Oracle;User ID=myuserID;Password=myPsswd;Data Source=host:port/service_name;"
sqlConn.ConnectionString = cs
sqlConn.CommandTimeout = 10000
sqlConn.Open
I get the following error messages:
1) The system cannot find message text for message text 0x80040e0c in the message file for OraOLEDB.
2) Sometimes, dependent on the iteration of the connection I use (IE a TNS connection), I get a TNS listener error message.
I currently have the ActiveX 6.1 Data Objects Library enabled. Furthermore, I am on a 64-bit machine with a 64-bit Oracle client installed. I have a 64-bit Office. I am quite certain I have a 64-bit ADO as well - my ODAC (if this is the same) is the same as the 64 bit version online. I have an ODP.NET of 2.12 and another with 4.121 in the registry. I just have an ODP.NET.Managed of 4.12.
This doesn't make much sense to me, how in one language I can connect with no issues, but in another I cannot!

I backtested using an earlier ActiveX Data Library - this solved it.
Thank you!!!!!

Related

How to connect Excel to Oracle database?

I am trying to connect Excel to my Oracle database using VBA.
Sub dbConnect()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(description=(address=(protocol=tcp)(host=mydb.domain.com)(port=1522))(connect_data=(sid=mydb))); uid=user; pwd=pw;"
con.Open (strCon)
End Sub
I get an error.
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I know from other questions and sources that the problem is most likely using the wrong version of the DSN.
However, I don't understand what I need to do to fix it.
My Windows is 64-bit, when I open the ODBC Data Source Administrator I see the following (among others):
Name: Excel Files, Platform: 64-bit, Driver: Microsoft Excel Driver
User DSN
Name: mydb, Platform: 32-bit, Driver: oracle in ORA121020_x86
under System DSN
What can I do to fix it? How do the connection string and the DNSs relate to each other? Should I change the version of one of the DNS and if yes how do I do that?
Edit:
The connection string is copied from the db connection in Oracel SQL Developer where I can access the db.
Ok I managed to fix it. My excel is 64 bit so in order to connect to the db, I had to create a System DNS for my connection that is also 64 bit. In order to do that, I had to go to the /Windows/system32 folder, choose the file odbcad32 and under system DNS add a new DNS with a 64 bit driver I had to download. Lets say I named that DNS abc
I then also changed the connection string that you can see in the above code to
strCon = "Data Source=abc;User=user;Password=pw"
According to this the connection string I used in the post above does not need a DNS, so I don't know why it didn't work, however after creating a new DNS as just described I switched to the new connection string that specifies a DNS.
And voila, after only several hours I was able to connect to my db.
Quick sidenote: As mentioned above, I edited the obcad32 file in /Windows/system32. This is the file for 64 bit DNS. There is a file with the exact same name in the folder /Windows/SysWOW64 that manages the 32 bit DNS, so if you have a similar problem as I had, pay attention to which file you edit.

Can't connect to Access DB, neither with OleDB, DAO, etc

I want to read and write data from a CATIA macro to and from an Access DataBase. I've got Windows 10 and Office 2013 on it (64bit Windows).
Unfortunately I can't connect to that Access DataBase from VBA. (From VB.NET works fine)
I tried it all:
Various connection strings (JET.4.0, ACE.12.0) etc with ADODB
-> Error that Provider cant be found
Connection via DAO
-> Various other errors
Any idea why I cant connect?
I referenced all DLLs possible to reference, etc.
Only idea I have that theres a problem with Access 2013 32bit and the 64 bit Windows?
I tried from Excel with the following code (source), it works like a charm.
Sub test()
Dim cnn As ADODB.Connection 'Requieres reference to the Microsoft
Dim rs As ADODB.Recordset 'ActiveX Data Objects Library
Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\someFolder\myDb.accdb;"
Set rs = cnn.Execute("SELECT * FROM versions")
While Not rs.EOF
Debug.Print rs(1), rs(2), rs(3)
rs.MoveNext
Wend
rs.Close
End Sub
if that doesn't work, the client PC may lack a piece of software ?

ADOBC Connection Fails on Windows 10 Machines Only

I'm fairly new to working with Access/VB (started 2 months ago) so bear with me.
I inherited a database that has an ADODB connection to Oracle that works perfect on the Windows 7 machines that it's been tested on (a total of 5), but gives the following error when tested on Windows 10 machines (total of 2). (All machines are running Access 2010).
Run-time Error '3709': The connection cannot be used to perform this operation. It is either closed or invalid in this context.
Here's the code:
Public Function PTMNConnect() As ADODB.Connection
Dim Cn As ADODB.Connection
Dim Conn As String
Conn = "DRIVER={Microsoft ODBC for Oracle};CONNECTSTRING=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=host)(PORT=port))(CONNECT_DATA=(SERVICE_NAME=PROD)));uid=username;pwd=password"
Set Cn = New ADODB.Connection
With Cn
.ConnectionString = Conn
.CursorLocation = adUseServer
.Open '**Errors Out on Open**
End With
Set PTMNConnect = Cn
End Function
I've been racking my brain and searching everywhere for a possible solution to this for the past two days with no luck.
Here's what I've tried/verified so far based on other posts I'd seen:
Verified that the Oracle client was installed
Ensured that the Path variable contained the necessary paths
Verified the references and file paths are the same on all machines
Any insight or references that you may be able to provide would be greatly appreciated!
I was able to come up with a fix for this!
It turns out that Windows 7 and Windows 10 have different versions of the {Microsoft ODBC for Oracle} driver which I believe is what was causing the error. I decided to use the Oracle supplied driver (which remains the same for each PC) rather than the Microsoft supplied driver (which, as I found out, varies).
Replacing the Conn string from above with the following code fixed my issue. (This route requires an existing DSN):
Conn = "DRIVER={Oracle in OraClient11g_home1}; Dbq=DSN_TNSServiceName; uid=username; pwd=password"

Connect to 32-Bit MS Access DB in a 64-Bit VB .Net application

I am very new to programming so I will require some extra help on figuring this out. I have a VB .NET application that provides an Add-In for a 64-Bit application. The task I am trying to accomplish is to open a connection to a 32-Bit MS Access database and lookup data from a table. Where this falls apart is the fact that a 64-Bit application cannot connect with a 32-Bit database. You can probably tell from my explanation that I barely know what I am talking about.
Everything I have researched on this topic comes to the same conclusion that I need to use an interprocess communication but do not explain how this is done and what I am required to do to make this happen.
Here is my connection setup in the VB .Net application:
Public Class MSDatabase
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Public Sub LoadDatabase()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "\\server3\databases\Quotes.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
End Sub
Public Function LookUpPart(D As Double, E As Double, F As Double, G As Double, Grade As String) As Boolean
myConnection.Open()
Dim str As String
str = "SELECT PartNumber, D, E, F, G, Grade FROM Parts"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
If D = dr("D") And E = dr("E") And F = dr("F") And G = dr("G") And Grade = dr("Grade") Then
Return True
End If
End While
myConnection.Close()
Return False
End Function
End Class
This fails when I try to open the connection with the error message stating that the provider Microsoft.ACE.OLEDB.12.0 is not registered on the local machine.
What I would like to know is how to use interprocess communication to set this up as a 32-Bit application called from my 64-Bit application.
Any help is greatly appreciated!
Thanks to jmcilhinney for their help with solving this issue. Read the comments under the question to see how we arrive at this solution.
SOLUTION: Using interprocess communication through a TCP socket connection you can pass data back and forth regardless of the bittedness of the host and client. In this case, the 64-Bit vb .net program written for an Add-In to another software can setup a TcpClient that uses Process.Start to first run a TcpListener in a console application developed for the x86 platform and then send the listener information for the database communication. The listener being a 32-Bit console application is able to find and use the 32-Bit provider for the OLEDB connection and pull the needed data from the Access DB. The data is then sent back to the client in the 64-Bit application.
For the TCP socket connection you can use a simple YouTube tutorial on a client/server TCP connection for vb.net.
For sending data I used a delimiter so that the data could easily be separated on the other end using Split.
We had the same problem and solved it by following the the instructions found here (look for the section titled "The Solution"). There you'll find a link to the appropriate driver you need to install.
The install seems to be necessary because with Office 2010 Microsoft changed the driver for accessing Access, Excel and so on. So it's not a problem with your code, but the environment it runs in.

How to connect VBA to postgreSQL and run query

I am trying to run a query from an Microsoft excel application and have not been able to connect successfully.
I have PostgreSQL 9.3 on my local machine, and am running 64 bit windows 7. I have a sample database name dvdrental which is a demo database.
I simply need to connect to the database, run a query, and view the output in my worksheet(or immediate window, either one resolves the connection issue).
Here is what I have so far which is not working.
Option Explicit
Public objConnection As ADODB.Connection
Public strConnection As String
Public Sub TestPostgresConnection()
Dim strConnection As String
strConnection = "Driver={PostgreSQL Unicode};Server=localhost;Port=5432; Database=dvdrental;UID=sa;PWD=wrox;"
Set objConnection = New ADODB.Connection
Set objRecordSet = New ADODB.Recordset
objConnection.Open strConnection
With objRecordSet
.ActiveConnection = objConnection
.Open "SELECT * FROM actor"
End With
Do While Not objRecordSet.EOF
Debug.Print objRecordSet.Fields(0).Value
objRecordSet.MoveNext
Loop
objRecordSet.Close
objConnection.Close
Set objRecordSet = Nothing
Set objConnection = Nothing
End Sub
Here is a list of my references;
Visual Basic For Applications
Microsoft Excel 14.0 Object Library
OLE Automation
Microsoft Office 14.0 Object Library
Microsoft Forms 2.0 Object Library
Microsoft Access 14.0 Object Library
Microsoft ADO Ext. 6.0 for DOL and Security
Microsoft ActiveX Data Objects 2.8 Library
Microsoft Windows Common Confrols 6.0 (SP6)
When I execute this test method TestPostgresConnection, I get "[Miscrosoft][ODBC Driver Manager] Data source name not found and no default driver specified"
My setup of postgres has been standard and I have simply followed the directions on their website for creating a local RDBMS for testing.
Can anyone tell me why I am not able to connect and run a query?
None of the solutions have worked so far. Thanks.
My answer is a general answer. Giving back to the community. So be nice. I had a similar question and I used the following to set it up.
Note: I suggest using DSN instead of the driver then you can use a named connection that has the password already, rather than having the password in your code.
These instructions were a huge help generally:
http://www.dashbay.com/2011/03/working-with-postgres-on-windows-via-odbc/
The download link in the link above didn't work for me. I found the ODBC downloads here:
https://www.postgresql.org/ftp/odbc/versions/msi/
I think I downloaded this one:
psqlodbc_09_05_0400-x86.zip
I used Konstantin's answer to get %WINDIR%\SysWOW64\odbcad32.exe from this link:
PostgresSQL ODBC Drivers on Windows 7 not showing up
I also downloaded MS Power Query here which I found helpful:
https://www.microsoft.com/en-us/download/details.aspx?id=39379
I am happy to edit my answer if I should add clarification.
Below is the sub for the query and below that is a sub that demonstrates how you use it.
Sub CcQueryPg(sSql As String, Optional sOdbcName As String = "ConnectionNameHere")
'Declare a Connection object
Dim cnDB As New ADODB.Connection
'Declare a Recordset Object
Dim rsRecords As New ADODB.Recordset
'Open the ODBC Connection using this statement
cnDB.Open sOdbcName
rsRecords.Open sSql, cnDB
'Close everything and set the references to nothing
rsRecords.Close
Set rsRecords = Nothing
cnDB.Close
Set cnDB = Nothing
End Sub
Sub SendQuery()
Call CcQueryPg("COPY sometablenamehere FROM '/mnt/somepathhere/somefilename.csv' DELIMITER ',' CSV HEADER;")
End Sub
The above file reference is to a file on a Linux machine. Your path format may differ.