Samples of VBA code I'm using in my daily tasks.

Tuesday, March 9, 2010

How To Build ODBC Connection String

I'm  working with MS Access and have many tables linked to Oracle and DB2. When I wanted to automate some process I needed to connect to DB2 and pass my ID and Password using VBA code. I spent many hours trying to guess the correct ODBC Connection String. Web site http://www.connectionstrings.com/ gave me some examples, but I couldn't make it work. I asked our DB2 admin for advice, and got an email saying that I just have to use my ID and Password????  What .... Really...  No help there.
Than one day while creating my first Pass-Trough Query I saw the string. It was so simple and strings I was trying to use were so close to this one, but still not exact and not correct. All I had to do was to copy the string into my porogram. If you have the same problem here is what you have to do to find the exact ODBC Connection String.
In Access Open New Query. Without adding tables close the Show Table dialog box. 
On  the Query menu, Point to SQL Specific, and click Pass-Trough


Than click on the menu bar Properties,  and clcik ... to build ODBC Connect String.


Select your Data Source where your DB2 tablese are located (on my system it's DB2A)


Enter your system/network ID and Password.


After you click YES to Save password in the connection string, you can see the string in the wizard box, so you can copy it and save the string in your program.  Now you can close the query without saving it.


Here is the code I'm using to connect to DB2 and Oracle. You can create a function and pass the UserID and password.
'---------------------------------------------------------------------------------------
Dim db As Database
Dim strConnect As String
 
strDB2id = "Your_DB2_UserName"
strDB2pw = "Your_DB2_Password"
strORAid = "Your_Oracle_UserName"
strORApw = "Your_Oracle_Password"

' DB2 connection string:
' "ODBC;DSN=DB2A;UID=Your_ID;PWD=Your_Password;MODE=SHARE;DBALIAS=DB2A;"
strConnect = "ODBC;DSN=DB2A;UID=" & strDB2id & ";PWD=" & strDB2pw & ";MODE=SHARE;DBALIAS=DB2A;"
Set db = DBEngine.Workspaces(0).OpenDatabase("", False, False, strConnect)
db.Close

' Oracle connection string for Oracle10 ODBC driver.
' "DSN=PRD26;SERVER=PRD26;UID=Your_ID;PWD=Your_Password"
strConnect = "DSN=PRD26;SERVER=PRD26;UID=" & strORAid & ";PWD=" & strORApw
Set db = DBEngine.Workspaces(0).OpenDatabase("", False, False, strConnect)
db.Close
'----------------------------------------------------------------------------------------------

1 comment: