Connect to Oracle database from python

Post date: Feb 19, 2015 6:23:33 AM

We can use package cx_Oracle. This blog from Joel is the best instruction ever; at least it works for me.

Here is an example or the code:

import pandas as pd
import cx_Oracle
## db parameters
user_name = 'myusernamehere'
password = 'mypasswordhere'
query = 'select * from mydbdb.table_name where rownum < 20 and creation_date > sysdate - 2'
## connect to the DW and query the data
dsn = cx_Oracle.makedsn('Thehostname', portnumber, 'Thedbname')
con = cx_Oracle.connect(user_name, password, dsn)
curs = con.cursor()
curs.execute(query)
## Convert the cx_Oracle object to pandas dataframe
headers = [ x[0] for x in curs.description]
data = curs.fetchall()
df = pd.DataFrame( data, columns=headers)
## display the dataframe
df
## The type conversion is also pretty accurate
df.dtypes

Someone package the whole thing into a function [here].

other resources

Another good tutorial by utexas here.