Installing Oracle (cx_Oracle) for Python

Installing Oracle for Python with Anaconda Python 3.x on Windows

The process of installing Oracle drivers into Python is complex. To use Python with Oracle
three components must all be inplace and be of the same version (Python 3.5 suggested)
and architecture (64-bit suggested). This tutorial assumes that you desire a Python 3.5
instance running in 64-bit. To do this, you must have installed:

  • Part 1: Anaconda Python 3.5 (64-bit)
  • Part 2: cx_Oracle for Python 3.5 (64-bit)
  • Part 3: Oracle 64-bit Instant Client (64-bit)

That perfect chain of 64-bit and Python 3.5 cannot be broken or you get a series of very
cryptic error messages. RGA INSTALLS 16-bit Oracle on Most Machines. This is a problem,
but it can be worked around.

Part 1: Anaconda Python 3.x (64-bit)

Run the following cell to determmine what sort of Python you have.

Make sure that the below says you are running 3.x, Anaconda and 64-bit. Note that you
have a Python version and an Anaconda Verison. Python version is displayed first.

First, see what version of Python you have installed and how many bits.

1
2
3
# Find out what type of Python you have (make sure to rerun this for your machine)
import sys
print(sys.version)

This should respond something like this:

1
3.4.4 |Anaconda 2.2.0 (64-bit)| (default, Feb 16 2016, 09:54:04) [MSC v.1600 64 bit (AMD64)]

Part 2: Install cx_Oracle (Python’s Driver)

Next you will need to install a binary of the cx_Oracle Python driver. This the Python
side of things and interfaces Python to the actual Oracle driver (that is installed in
Step 3). Issue the below command to the command line.

1
pip install cx_Oracle

You can also download a binary image directly, this is usually not necessary on Windows.
The link below takes you to binary images:

Part 3: Install Oracle Driver (Oracle’s Driver)

Python needs a 64-bit Oracle driver. Download the Oracle 12 instant client.

The above link requires you to have an Oracle ID. If you wish to just obtain the file,
you can get it from the following RGA share:

This is simply a zip file, I suggest unzipping it to c:\Oracle, this will create a directory such as:

1
C:\Oracle\instantclient_12_1

Does it Work?

Now it is time to test the drive. If you can execute the following command, and not get
an error, then you have successfully configured Oracle for Python.

1
2
3
4
# Use the directory you unzipped the instant client to:
import os
os.chdir("C:\\Oracle\\instantclient_12_1")
import cx_Oracle

Simple Oracle Query

1
2
3
4
5
6
7
8
9
10
11
ORACLE_CONNECT = "schema/password@(DESCRIPTION=(SOURCE_ROUTE=OFF)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host)(PORT=1521)))(CONNECT_DATA=(SID=sid)(SRVR=DEDICATED)))"

orcl = cx_Oracle.connect(ORACLE_CONNECT)
print("Connected to Oracle: " + orcl.version)

sql = "select * from MYTABLE"
curs = orcl.cursor()
curs.execute(sql)

for row in curs:
print(row)