Connecting To Oracle Directly (Without settings.py)
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):
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:
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.
More from Aware Labs
- Constructive reasons to use Django instead of Rails (Proxied)
- Retiring Old Posts To Keep Django Fresh
- Django Generic Relations Made Easier
- Using Django Models In Batch Jobs
- WordPress Adventure – NoScript Hack Solved
Aware Labs Recommends
- How Not To Use Social Media (The Arkayne Blog)
- How To Write Better Blog Posts (The Arkayne Blog)
- Beginners Guide to SEO (The Arkayne Blog)
-
North Carolina Furniture

![Recommend [AwareLabs]](http://s3.amazonaws.com/arkayne-media/img/badge/logo-recommend-badge-medium.png)