« Add P2P Social Bookmarking To Your Pages | Home | Shark Or Bear – Its A Killer Website »
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):
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
- Add P2P Social Bookmarking To Your Pages
- WordPress Adventure – NoScript Hack Solved
- Constructive reasons to use Django instead of Rails (Proxied)
- Django Generic Relations Made Easier
- Using Django Models In Batch Jobs
Aware Labs Recommends
- Popularizing Django — Or Reusable apps considered harmful. (USwaretech)
- Getting Django up and running on Centos 5.2 with Apache(mod_python) and MySQL (Dougal Matthews)
- Why you should try Django : Agility (Dougal Matthews)
Topics: Batch Code, Code Snippets, Environment Setup, Model Revisions | Comments
-
North Carolina Furniture