tags:

views:

946

answers:

3

How do you connect to a remote server via IP address in the manner that TOAD, SqlDeveloper, are able to connect to databases with just the ip address, username, SID and password?

Whenever I try to specify and IP address, it seems to be taking it locally.

In other words, how should the string for cx_Oracle.connect() be formatted to a non local database?

There was a previous post which listed as an answer connecting to Oracle via cx_Oracle module with the following code:

#!/usr/bin/python

import cx_Oracle
connstr='scott/tiger'
conn = cx_Oracle.connect(connstr)
curs = conn.cursor()

curs.execute('select * from emp')
print curs.description
for row in curs:
    print row
conn.close()
A: 

I wish someone had an answer to this question :(

They did, just not soon enough.
Craig Trader
+4  A: 

You can specify the server in the connection string, e.g.:

import cx_Oracle
connstr = 'scott/tiger@server:1521/orcl'
conn = cx_Oracle.connect(connstr)
  • "server" is the server, or the IP address if you want.
  • "1521" is the port that the database is listening on.
  • "orcl" is the name of the instance (or database service).
Jeffrey Kemp
This may not work in all environments. In my case it doesn't work with Oracle InstantClient 11g and Python 2.6 on 64-bit Windows 7. The DSN method is more portable.
Craig Trader
@Craig: thanks for the heads-up - can you tell me how it didn't work? What error is reported?
Jeffrey Kemp
ORA-12514. Basically the listener on `server` doesn't recognize `orcl` as an instance. I couldn't make heads or tails of that, so I fired up a packet tracer, and the DSNs that are generated (for the Connect packet) are significantly different. The server is Oracle 10g, which may be significant.
Craig Trader
@jeffrey, I re-ran my packet traces. A connection made with `user/pass@host:port/dbname` ends up using `dbname` as the `SERVICE_NAME` instead of the `SID`, which fails for Oracle InstantClient 11g when talking to an Oracle 10g server.
Craig Trader
+4  A: 

I like to do it this way:

ip = '192.168.0.1'
port = 1521
SID = 'YOURSIDHERE'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)

db = cx_Oracle.connect('username', 'password', dsn_tns)

One of the main reasons I like this method is that I usually have a TNSNAMES.ORA file lying around someplace, and I can check that the dsn_tns object will do the right thing by doing:

print dsn_tns

and comparing the output to my TNSNAMES.ORA

Kevin Horn
+1 for the more portable solution.
Craig Trader