Django Aware

« | Home | »

Connecting To Oracle Directly (Without settings.py)

By Paul Kenjora | October 23, 2007

I recently ran into an situation where I needed to connect to both an Oracle DB and my local DB simultaneously in Django. I was porting data between the two. After spending an hour online hunting around for how to use cx_Oracle I finally found a working example. I first got things running in my settings.py file but then needed a raw connection to a second database. Here is how I did it:

Installing cx_Oracle module the easiest way possible (without root):

Grig Gheorghiu’s Excellent Source And Instructions

Minor note to the above, his setup.py is designed to go off the ORACLE_HOME env variable. I short circuited it in the code and just pointed it directly to where the "xa.h" file lived. Once you generate "cx_Oracle.so" then simply copy it to a PYTHONPATH location.

Oracle configured in settings.py (for reference):

settings.py


DATABASE_ENGINE = 'oracle' # 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'.
DATABASE_NAME = 'dbname' # Or path to database file if using sqlite3.
DATABASE_USER = 'username' # Not used with sqlite3.
DATABASE_PASSWORD = 'password' # Not used with sqlite3.
DATABASE_HOST = 'host.com' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '1534'

The above code is not required for accessing Oracle directly but is given as a reference for how the parameters are used in the function below.

Oracle accessed directly:

batch.py


dsn = cx_Oracle.makedsn(host.com', int(1534), 'dbname')
my_db = cx_Oracle.connect('username', 'password', dsn )
cursor = my_db.cursor()
cursor.execute("SELECT a, b, c FROM sometable")
rows = cursor.fetchall()

By the way if you get the "ORA-12154: TNS: could not resolve service name" error then your dsn is incorrectly constructed. For some reason you must use cx_Oracle.makedsn.

Topics: Batch Code, Code Snippets, Environment Setup, Model Revisions | Comments

  • This is a cool screen idea ! It is very interesting indeed.Thank you for your info.i love to read all info.

    regards
    Wilson mark
    ______________________________________________
blog comments powered by Disqus