Oracle Database Connection in Python


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.

Example

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.

Example

import cx_Oracle
# Connecting to DB
try:
   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
   finally:
   if cursor:
      cursor.close()
   if con:
      con.close()

Running the above code gives us the following result −

Output

Table Created

Updated on: 28-Dec-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements