Oracle Database Connection in Python

PythonServer Side ProgrammingProgramming

Python can connect to oracle using a python package called cx_Oracle. Oracle is one of the famous and widely used database and python’s data processing features are leverages well using this connectivity. In this article we will see how we can connect to oracle database and query the DB.

Installing cx_Oracle

We can use the below command to install the python package which can be used for establishing the connectivity.


pip install cx_Oracle

Connecting to Oracle

Now using this module we can connect to a oracle database which is accessible through the oracle service name. We create a cursor and execute the SQl query through the cursor for creating a table. All this is handled through a try and except structure to catch any exception or failure in database connectivity.


import cx_Oracle
# Connecting to DB
   con = cx_Oracle.connect('username/password@servicename')
   cursor = con.cursor()
   #Creating a table
   cursor.execute("create table TableName(COL1 VARCHAR2(200),\COL2 NUMBER(8))")
      print("Table Created")
except cx_Oracle.DatabaseError as e:
   print("Problem connecting to Oracle", e)
   # Close the all database operation
   if cursor:
   if con:

Running the above code gives us the following result −


Table Created
Published on 28-Dec-2020 15:40:19