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

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.

Related

Excel VBA database access through ODBC not ADODB

I am working on an Excel file that connects to a SQL database to update parameters on a piece of production machinery based on an analysis of part quality data. The file has been working in production for some time but a recent hacking attack on my company has caused us to review the security of all of our systems.
The old file version used ADODB with a hard-coded user name a password with narrowly defined database permissions. This meant any quality or engineering employee could run the Excel utility without being explicitly given server/database access. With our new security review, I wanted to switch the file to use windows authentication but I ran into some issues. It seems that using windows authentication through ADODB requires not just a database user, the automation team has permissions to create, but also a server login mapped to the database user which only an IT admin can create. I also worry that adding a large number of server-level users is not a wonderful idea.
The actual piece of production equipment uses a system-level ODBC connection with window authentication. This connection works fine with a database user without a server login. Because ODBC doesn't seem to need a server login it would make the management of the Excel file users much simpler and would allow the team in charge of the equipment and its database to handle it without IT.
Unfortunately, I have been unable to figure out how to execute queries and get results in VBA with an ODBC connection. I have tried Workbook.Connections("ODBCName").CommandText with an ODBC connection stored in the workbook but I don't see a way to directly get the result. The only option I can see is to map the query to cells in a hidden table and read them in VBA but this seems hackish. Also, I'm not sure how this would work for the results of queries other than SELECT like INSERT or UPDATE.
Any help would be greatly appreciated. An example of my old code is here, there are more routines that make similar queries:
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * FROM Table.dbo.PART_INSPECTION_LOG WHERE PART_NUM = 'PartNo' AND DATA_TIME = " & dataTime
rs.Open strSQL, cn
If (rs.BOF And rs.EOF) = True Then
linear_err = (Sheets("Adjustment").Range("E24").Value)
rotational_err = (Sheets("Adjustment").Range("N24").Value)
strSQL = "INSERT INTO Table.dbo.PART_INSPECTION_LOG (PART_NUM, TOOL_ID, USER_NAME, DATA_TIME, LINEAR_ERROR, ROTATIONAL_ERROR) VALUES ('PartNum', 'ToolNum', "
strSQL = strSQL & "'" & Application.UserName & "', "
strSQL = strSQL & dataTime & ", "
strSQL = strSQL & linear_err & ", "
strSQL = strSQL & rotational_err & ")"
cn.Execute strSQL
End If
cn.Close

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.

Accessing Oracle SQL Developer database from VBA

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.

Unable to connect to DB from VBA but able to connect from Access

I'm able to connect to a database using Access, but not from VBA. In Access, I use the server name, Windows NT Integrated Security,and the database name. In VBA, I've tried many variations of variable names and values in the connection string, and the db.Open command always fails. I generally get an error about not being able to find an installable ISAM, or Multiple-step OLE DB operation generated errors. Is there a way to determine what I can use as a connection string from the working Access connection? One example of code that fails with the latter error:
Dim db As Object
Dim adoRS As Object
Set db = CreateObject("ADODB.Connection")
Set adoRS = CreateObject("ADODB.recordset")
db.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Server=sql03;" & _
"Database=db1;" & _
"Integrated Security=SSPI;"
The provider you as using in the connection string is for MS Access.
If thats the correct database then do the following.
Add the refrence "Microsoft Office 14.0 Access Database Engine object library.
Dim cnString, query As String
Dim rs As New ADODB.Recordset
'If older version of MS access then try Provider=Microsoft.Jet.OLEDB.4.0;'
cnSTring= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<Path>;Jet OLEDB:Database Password=<Pass>;"
query = "SELECT * FROM TABLE"
rs.Open query, cnString, adOpenStatic, adLockOptimistic

OLEDB Connection from Excel to Oracle Issue

Everyone,
A VBA problem has been killing me the past two days. I have a Macro Based Model in Excel that has data sets bought into the spreadsheets from Oracle via OLEDB. To illustrate the problem simply I have created two functions within the Model. One using ODBC("odbc") and another using OLEDB("OraOLEDB"). The code was working completely fine last week and it has not been changed.
Now, however I get an error message that states "Run-Time Error '424': Object Required when I execute the line "conn.Open strCon" in sub "OraOLEDB".A connection can't be established with the database! So when I am trying to establish a connection to the database with that line of code, it fails. What is interesting is that via ODBC, a connection can be established. The line "conn.Open strCon" in sub "odbc" executes successfully and I am able to establish a connection to the database.
I did not change anything in the Excel Model but I did have a bunch of windows updates recently. I don't know if that corrupted anything. I think it may have. The reason why I don't want to use the ODBC connection is that it is significantly slower. I get run times 10x faster using OLEDB. Please let me know if you can help.
Sub odbc()
Dim conn As Object
Dim strCon As String
strCon = "Driver={Microsoft ODBC for Oracle};
CONNECTSTRING=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=xxx)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=xxx)));
uid=xxx;pwd=xxx;"
Set conn = CreateObject("ADODB.Connection")
conn.Open strCon
End Sub
Sub OraOLEDB()
Dim conn As Object
Dim strCon As String
strCon = "Provider=OraOLEDB.Oracle;
Data Source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)
(HOST = xxx)(PORT = 1521))
(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = xxx)));
User Id=xxx;Password=xxx"
Set conn = CreateObject("ADODB.Connection")
conn.Open strCon
I see the host for the OLEDB connection is modn-ast-fdb1. ... while for the ODBC connection you have modn-ast-tdb1. ... Shouldn't the host be the same?
This means Set conn = CreateObject("ADODB.Connection") returns nothing. Check ADODB.dll registration. Alternatively you may use
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
and you'll see if ADODB is available at the moment you edit the script not waiting for runtime errors.