Accessing Oracle SQL Developer database from VBA - sql

New to VBA and returning to SQL after 15 years. I'm am trying to use VBA to run SQL commands to download data into excel for further manipulation.
I have SQL Developer installed on my machine and I am able to access the database using the UI. I have figured out how to connect to the database and run a query within the SQL Developer interface, but honestly, I'm not an IT guy.
Any ideas how to do this? Even basic command line commands to connect to the database and run the query would be helpful.
I found this code on another site, but I'm having trouble getting my connection string to work. My macro errors out on the cnn.Open statement and says the Provider is not installed. I think it's because PROVIDER is set up for a different SQL Database type, but I can't seem to get the connection string to work.
I know my username and password, which I have successfully used to connect in the SQL Developer UI. I'm not sure what to put for remote IP address or database. Would that be the hostname and the SID in the connection properties dialog in SQL Developer? (The hostname looks more like a url without the http than an ip address. Not sure if hostname and ip address is an interchangeable term).
Sub Download_Reports()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=ORAOLEDB.ORACLE;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
I'm needing help with my connection string. Can anyone help me with this?
I'm connecting to a database via Oracle SQL Developer. I am able to connect within the UI by providing the following items:
Connection Name - got it.
myUsername - got it.
myPassword - got it.
Connection Type = Basic, Role = default
myHostname - got it.
myPort - got it.
mySID - got it.
However, I am unable to get my connection string to work in VBA. When I run the script I get
"Run-time Error '3076'. Provider cannot be found.
It may not be properly installed" on the line beginning with cnn.open.

Related

Is there a way to specify a proxy user id in a VBA Macro to connect to oracle?

I am currently trying to connect to an Oracle database from VBA. Below is the code I am running in VBA to try to establish the initial connection. Unfortunately, this code produces an “ORA-01017” error mentioning that my username/password is invalid. I have SQL Developer installed and when I try to login with the same credentials/info, I successfully connect. I also tried instead setting UID = userid in the VBA code below and the connection didn’t throw an error, but I can’t query any tables. The same thing happens if I try the same in SQL developer.
After doing some reading, it looks like the info in the brackets is my proxy user id and I need to somehow specify that separately from my UID, but I can’t figure out how I would go about that. Has anyone else had any experience with this or have any guidance? Let me know if there is any additional details I can provide.
Sub Ora_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.recordset
Set con = New ADODB.Connection
Set rs = New ADODB.recordset
StrCon = "Driver={Microsoft ODBC for Oracle}; Uid=userid[database name];Pwd=UserPWD;" & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=HostName)(PORT=1521))" & _
"(CONNECT_DATA=(SERVICE_NAME=XXXX)));"
con.Open (StrCon)
End Sub
It doesn't look like its possible to connect to proxy user with ADODB .
One another alternative is to use alter session set current_schema = Proxy_user run this after you open the session.
The only trouble with this is that the grants should be there for the actual user, here proxy user just allows us to avoid using identifiers.

VBA is unable to create a connection to a remote SQL Database

I've created an excel front end interface to connect with and manipulate an SQL database. I recently received a laptop, and would like to be able to manipulate the data from excel on said laptop. I established a connection using SQL Server Management Studios to the database.
I've tried to update my excel file; however, the VBA code can not connect to the SQL database. I've changed a few of the variables around and set Integrated Security too, but nothing has worked so far. The error message readouts can be seen here:
Here is the code related to the DB connection:
Dim cnSQL As ADODB.Connection
Set cnSQL = New ADODB.Connection
cnSQL.Open "Provider = SQLOLEDB; Integrated Security = SSPI, Data Source = IP Address,Static TP Port; UID = username; PWD =pwd#; Initial Catalog = database"
The error message highlights the second line of code. I'm hoping to be able to connect to the DB from my laptop.
After struggling for a few days, I finally got this to work. There are two important steps you need to take to make excel work with a Remote SQL network. First here is the code used to connect:
Dim cnSQL As ADODB.Connection
Dim ServerName As String
Dim DatabaseName As String
Dim userID As String
Dim password As String
ServerName = "IP Addresss,Port"
DatabaseName = "DB Name"
userID = "username"
password = "pwd"
Set cnSQL = New ADODB.Connection
sqlCommand.ActiveConnection = cnSQL
After I changed the code to this, I got a new error: "optional feature not implemented." To fix this error, I changed the data type of all 'adDate' to 'adDBTimeStamp.' This works for some reason, I don't know why. It works.

DSNless connection to Oracle database using DAO Database object in VBA

it's possible to use DSNless connection with wiht an object created from DAO Database class in VBA.
The connection to database using ODBC connection works as expected, however if you use other connection string types as mentioned www.connectionstrings.com the connection is not established.
public Sub dbConnectTest()
Dim myDB As DAO.Database
Dim conn As String
Dim tns As String
Dim odbcString as String
odbcString = "ODBC;DSN=Location Name;UID=ANUSER;PWD=apassword;DBQ=A_TNS_NAME"
' this part works
Set myWorkspace = DBEngine.CreateWorkspace("APPNAME", "admin", "")
Set myDB = myWorkspace.OpenDatabase(Name:="", Options:=dbDriverNoPrompt, ReadOnly:=True, _
Connect:=odbcString)
' same here
Set myDB = OpenDatabase("", False, False, "ODBC")
' any of below part don't work
odbcString = "Driver=(Oracle in XEClient);dbq=server:1980/SID;UID=ANUSER;PWD=apassword;"
odbcString = "Driver={Oracle in OraHome92};Dbq=A_TNS_NAME;UID=ANUSER;PWD=apassword;"
odbcString = "Driver={Microsoft ODBC for Oracle};CONNECTSTRING=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=server)(PORT=1980)))(CONNECT_DATA=(SERVICE_NAME=SID)));Uid=ANUSER;Pwd=apassword;"
Set myDB = OpenDatabase("", False, False, odbcString)
end sub
I want to change the connection string due to the fact that even if myDB object is set to nothing after a user logout, when a new login is requested with a new password the old connection string is somehow preserved and instead of a connection error a successfully connection object is retrieved.
I was able to connect to an Oracle 11g instance using the following connection string and call to OpenDatabase. I'm using the version of DAO available through the reference "Microsoft Office 16.0 Access database engine Object":
' Construct connection string
oracxnstr = "Driver={Microsoft ODBC for Oracle};Server=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=fake.url.com)(PORT=fakePortNo))(CONNECT_DATA=(SID=fakeSID)));Uid=fakeUid;Pwd=fakePw;"
I've obviously used fake parameters in this string so I'm not exposing my database.
' attempt to connect to oracle
Set oradb = dbws.OpenDatabase("", 1, True, oracxnstr)
The Microsoft DAO documentation is woefully inadequate, so I'm pointing out the differences between my code and yours that might be relevant:
I'm using the connection string parameter "Server" instead of "CONNECTSTRING." However, either one works in my system.
I'm using the connection string parameter "SID" instead of "SERVICE_NAME." This also did not make a difference... this time. But for reasons I don't understand, I know that it has made a difference in the past. I don't understand why it does sometimes make a difference. (I'm an Oracle novice but I think the Oracle configuration has something to do with it.)
For the 2nd parameter to the OpenDatabase method, I'm using 1 instead of true. This is the dbDriverNotPrompt enumerated constant. If I change to true, this also doesn't make a difference.
If I use DAO 3.6 I do get a run-time error 3151 "ODBC connection failed." I'm wondering if the older version isn't able to handle DSN-less or TNS-less connection strings to Oracle?
The only other difference I can think of is that maybe your Oracle username/password account has Read Only permissions, while the 3rd parameter to the OpenDatabase method is set to false?

The microsoft access database engine cannot find the input table or query 'dbo'.. (VBA, Access2010)

Helllo!
I'm an MS Access-beginner. After an upgrade from Access2003 to Access2010 I am changing the database connection of our MS Access-Application from ODBCDirect (not supported anymore) to ADODB.
After (hopefully) successfully establishing a DB connection over an ADODB.Connection object I am initializing an ADODB.Command object:
Dim qdfWork As ADODB.Command
...
Set qdfWork = New ADODB.Command
Set qdfWork.ActiveConnection = CurrentProject.Connection
qdfWork.CommandText = "[dbo].[storedProcedureName]"
qdfWork.CommandType = adCmdStoredProc
qdfWork.Parameters.Refresh 'HERE THE ERROR-MESSAGE OCCURS
...
There is a stored procedure with the exactly same name "[dbo].[storedProcedureName]" stored on the server, but I still get the error-message:
"the microsoft access database engine cannot find the input table or query 'dbo'. Make sure it exists and that its name is spelled correctly."
If I don't write "[dbo]" in the CommandText I still get the same message, telling that "[storedProcedureName]" can't be found.
Here is my ADODB.Connection.connectionString:
"Driver={Microsoft Access Driver (*.mdb)};Dbq=\\folder1\folder2\User1\Database.mdb; Uid=Admin;Pwd=password;"
The connection via this connectionString works fine I think, I don't get any error-messages when connecting to the DB.
I checked that CurrentProject.Connection is really the connection I need.
I don't understand why my Application can't find this stored procedure although it is stored on the server.
Thanks for reading

Access remote sql server using VB.NET

I've found a few examples of using vb.net to access an sql database, so far none of them have worked . They all involve using DataReaders. Maybe its the fact that the sql db is not on the same machine as the application.
I was just wondering if anyone had a more comprehensive example of using VB.NET to access a remote sql server.
Thanks!
EDIT:
I've received a few helpful comments an replies already. So far my connection string looks like:
"server=sqlblah.myhost.com;uid=myuser;pwd=pass;database=testdb"
Probably also good to mention their is no editing of the tables a this point, just reading.
Check out the SQLClient class.
One convienent way to access a SQL database is to fill a DataSet object with query data with a DataAdapter object.
Dim sSQL As String = "SELECT * FROM ???"
Dim conn As New SqlClient.SqlConnection("connection string")
Dim da As New SqlClient.DataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds, "TABLE NAME")
You can then access the "TABLE NAME" table in the DataSet object.
The "connection string" is obviously your SQL connection string.
Use the sSQL string to query as necessary.
Quick side note - a helpful tool for creating connection strings:-
Open up a text document (notepad, wordpad etc) and save a blank document with the extension ".UDL".
This will give you a "Data link Properties" mini app.
Open up the app and change the provider in the "Provider" to whichever provider you need (in this case OLE DB Provider for SQL Server).
You then need to build up the connection in the connection tab.
Once you have chosen the criteria (ServerName (the drop down list will show you all visible Servers), Security permissions,Database (this drop down list will be populated based on the server chosen)) you can test your connection (to make sure you have permissions etc).
Click ok to close the App, rename the file to have a ".txt" extension and re-open in a text editor, hey presto, one built up connection string (as below).
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=YOURDBNAME;Data Source=YOURSERVERNAME